項目中用LayoutInflater加載xml布局一直飄黃警告,上網搜了搜發現沒有解釋明白的,到是找到了一篇外國的博文,但是竟然是英文。。。幸好以前上學時候的英語不是很差加上谷歌的輔助,簡單翻一下!
原文地址:http://www.cnblogs.com/kobe8/p/3859708.html
參考博客:http://blog.csdn.net/ccfcccfc/article/details/40984971
錯誤用法:
inflater.inflate(R.layout.my_layout, null);
加載xml布局常用的有這兩個方法:
inflate(int resource, ViewGroup root)
resource:將要加載的xml布局
root:指定“將要加載的xml布局”的“根布局”
inflate(int resource, ViewGroup root, boolean attachToRoot)
attachToRoot:是否將解析xml生成的view加載到“根布局”中
注意:這里的參數root的設置很關鍵,會影響到xml解析生成的view;如果設置成null即沒有指定“根布局”的話,xml的最外層根布局設置的Android:layout_xxx等屬性不會生效,因為android:layout_xxx等屬性是在根布局中獲得的;
第三個參數如果設置為:true,表示xml布局會被解析並加載到“根布局”中,如果為false,則會生成一個view並且不會加載到根布局中,但是這個view的類型取決於第二個參數根布局的類型,所以如果xml布局中如果設置了一些根布局類型中不存在的屬性則不會有效果。下邊是一個例子:
布局代碼:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
如果你的adapter中加載布局寫成這樣即不指定“根布局”:
LayoutInflater.from(context).inflate(R.layout.list_item, null);
運行效果
發現
android:layout_height=”50dp”
android:layout_margin=”50dp”
這兩句代碼沒有效果,這是因為沒有指定根布局,所以根布局里設置的android:layout_xxx等屬性並沒有起作用;
如果將adapter中加載布局代碼改為:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
運行效果:
我們發現android:layout_height=”50dp” 已經有效果了
但是layout_margin沒有起作用,這是因為我們上邊設置的“根布局”是ViewGroup,他不能識別layout_margin屬性,在線性布局里才會有這個屬性。
如果將adapter中改為:
- 1
- 2
- 3
- 1
- 2
- 3
最終運行效果會發現
android:layout_height, android:layout_margin都已經有效果了。