android中include標簽是為了便於控件的覆用的一個很好解決方案。
但是也有一些需要注意的地方,做此記錄,便於以后查看。
include標簽用法。
1.新建一個xml文件,命名 head.xml
head.xml文件內容如下:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/index_linear_foot" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <ImageView android:id="@+id/head_btn_refresh" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
2.新建一個布局文件,命名 main.xml
main.xml文件內容如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <include android:layout_width="fill_parent" android:layout_height="wrap_content" layout="@layout/head" /> </LinearLayout>
注意:上面我們的include標簽中是沒有為它指定id的。
3.新建一個MainActivity,設置布局文件為main.xml;
4.假設我現在需要在代碼中為head.xml中的RelativeLayout容器設置背景圖片。
代碼如下:
//獲得布局容器對象 RelativeLayout head = (RelativeLayout)findViewById(R.id.index_linear_foot); //設置背景圖片 head.setBackgroundResource(R.drawable.head);
這樣就OK了。
5.剛剛說到,我們的include標簽中是沒有為它指定id的,假設我們現在的main.xml文件布局容器是RelativeLayout,而我需要把某個控件放在head.xml下面。就需要使用到RelativeLayout布局容器的特有屬性 android:layout_below="" 屬性。還需要為include指定id屬性。
那我們的main.xml文件變成如下:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <include android:id="@+id/main_head" android:layout_width="fill_parent" android:layout_height="wrap_content" layout="@layout/head" /> <ListView android:id="@+id/listview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/main_headb" /> </RelativeLayout>
那接下來我們在運行我們的實例,結果發現,代碼在運行到head.setBackgroundResource(R.drawable.head);
這一句的時候拋異常了
java.lang.NullPointerException
原來:如果include指定了id的話,就不能直接把它里面的控件當成主xml中的控件來直接獲得了,必須先獲得這個xml布局文件,再通過布局文件findViewById來獲得其子控件。
代碼如下
View layout = getLayoutInflater().inflate(R.layout.head, null); RelativeLayout head= (RelativeLayout)layout.findViewById(R.id.index_linear_foot); //設置背景圖片 head.setBackgroundResource(R.drawable.head);
2013.11.29--今日又發現一個問題 如果include 里就一個控件,這 inlcude的id 就代表這個控件,如果你用了控件的id 將無法找到它。如果不是一個 include 的id 代表 這個xml最外層的控件id!!
原文http://blog.csdn.net/xyz_lmn/article/details/7197464)感謝 解決了這個麻煩
后記:
在Fragment里要用onCreateView()方法里的View來findviewbyid 才可以找到並設置背景