標籤:android
一、首先看帶三個參數的inflate方法:
public View inflate (int resource, ViewGroup root, boolean attachToRoot)
1、如果root不為null,且attachToRoot為TRUE,則會在載入的布局檔案的最外層再嵌套一層root布局,這時候xml根項目的布局參數當然會起作用。
2、如果root不為null,且attachToRoot為false,則不會在載入的布局檔案的最外層再嵌套一層root布局,這個root只會用於為要載入的xml的根view產生布局參數( 官方原話:If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.),
這時候xml根項目的布局參數也會起作用了!!!
3、如果root為null,則attachToRoot無論為true還是false都沒意義!即xml根項目的布局參數依然不會起作用!
二、再看帶兩個參數的inflate方法:
public View inflate(int resource, ViewGroup root)
查看源碼:
public View inflate(int resource, ViewGroup root) { return inflate(resource, root, root != null); }也就是說
1、當root不為null時,相當於上面帶三個參數的inflate方法的第2種情況
2、當root為null時,相當於上面帶三個參數的inflate方法的第3種情況
三、實戰—————以listview來驗證上面的理論
大家肯定遇到過在ListView的item布局中設定的高度沒有效果的問題。
item_lv_test.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="100dip" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="test" /></LinearLayout>
adapter的getView方法:
public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflate(R.layout.item_lv_test, null); } return convertView;}如果用上面的代碼會發現設定100dp是無效的。而如果換成下面的代碼就可以了。
public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflate(R.layout.item_lv_test, parent, false); } return convertView;}
這裡你該會想一想為什麼很多需要顯示View的方法中都有ViewGroup這個參數。
所以有些人會說在跟布局中設定是無效的,要再嵌套一層布局。這樣是錯誤的,會造成布局層級增多,影響效能
參考:http://blog.csdn.net/guolin_blog/article/details/12921889
https://github.com/CharonChui/AndroidNote/blob/master/Android%E5%AD%A6%E4%B9%A0%E5%8A%A0%E5%BC%BA/LayoutInflater.inflate%E8%AF%A6%E8%A7%A3.md
【android】LayoutInflater.inflate方法的詳解及xml根項目的布局參數不起作用的問題