include的作用就是重复使用同一段代码,提高代码的重用性。具体说就是,通过include 在 某布局 a.xml 中引用 B.xml布局文件,这个b.xml可同时被多个布局同时使用,所以达到了同一段代码重用的效果。
在使用include 的时候,通常需要在其外层包裹一个布局,如下:
1 <LinearLayout 2 android:id="@+id/mLinearLayout" 3 android:layout_width="match_parent" 4 android:layout_height="60dp" 5 android:layout_gravity="bottom"> 6 7 <include layout="@layout/include1" /> 8 9 </LinearLayout>
这个布局是用来设置 include 的位置、宽高等属性的。
当然还有一种方式就是可以直接在include 里面设置它的这些属性,这里不举例了。仅说一下在include 外面包裹的用法。
下面用一小段例子来说明:
include1.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <TextView xmlns:android="http://schemas.android.com/apk/res/android" 3 android:text="这是第一个布局文件 !" 4 android:layout_width="wrap_content" 5 android:layout_height="wrap_content"> 6 </TextView>
include2.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <TextView xmlns:android="http://schemas.android.com/apk/res/android" 3 android:text="这是第一个布局文件 " 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" > 6 </TextView>
用 include 引用以上两个布局文件(include1.xml 和 include2.xml)
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="fill_parent" 4 android:layout_height="fill_parent" 5 android:orientation="vertical" > 6 7 <LinearLayout 8 android:id="@+id/mLinearLayout3" 9 android:layout_width="match_parent" 10 android:layout_height="60dp" 11 android:layout_gravity="center" > 12 13 <include layout="@layout/include1"/> 14 </LinearLayout> 15 16 17 <LinearLayout 18 android:id="@+id/mLinearLayout" 19 android:layout_width="match_parent" 20 android:layout_height="60dp" 21 android:layout_gravity="bottom"> 22 23 <include layout="@layout/include2" /> 24 </LinearLayout> 25 26 </LinearLayout>
通过LinearLayout的包裹对其设置在当前界面的位置,如include1 设置在布局中间,include2 设置在布局底部。