標籤:android android開發
在做布局時,經常有些部分是重複的,比如title或者foot的地方,最簡單的辦法當然是直接複製過去,
這裡介紹include的用法,有過c++或者c經驗的同學一看就明白了,就是把另一個布局包含進來.
先看下實現的效果:
裡面上下各有兩個文字布局,是用include包含進去的,直接看代碼
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <include android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginTop="30dp" layout="@layout/header" /> <ViewStub android:id="@+id/pic_stub" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:inflatedId="@+id/pic_view_id_after_inflate" android:layout="@layout/pic_view" /> <include layout="@layout/footer" /></RelativeLayout>
很清楚的兩個include,至於中間的viewstub,在下一篇部落格裡講解
地址:http://blog.csdn.net/jason0539/article/details/26132267
代碼裡我用了兩個include,
第一個比較複雜,設定了屬性,讓它在布局頂部
第二個比較簡潔,屬性都沒有設定,但是位置卻很正確,在布局的底部,
這樣的目的是為了展示include屬性的兩種設定方式,可以在include標籤裡設定,也可以在所要引用的布局裡面設定
所包含的兩個布局檔案如下:
header.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="0dp" android:layout_height="0dp" android:gravity="center_horizontal" android:text="Header Without Properties!" ></TextView>
在這裡面的寬度高度都設定為0了,目的就是要在布局中通過include標籤設定它的布局
footer.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginBottom="30dp" android:gravity="center_horizontal" android:text="With Properties!" />
這個的屬性設定的很完整,所以在布局中include標籤裡就什麼都沒設定,直接引用就行了,
兩種方法效果相同,看個人喜好來用.
jason0539
微博:http://weibo.com/2553717707
部落格:http://blog.csdn.net/jason0539(轉載請說明出處)