關於LayoutInflater的錯誤用法(警告提示:Avoid passing null as the view root)


項目中用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布局中如果設置了一些根布局類型中不存在的屬性則不會有效果。下邊是一個例子: 
布局代碼:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="50dp" android:layout_margin="50dp" android:gravity="center" android:orientation="horizontal" >
<TextViewandroid:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView1" />
<TextViewandroid:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView2" /></LinearLayout>
  • 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中加載布局代碼改為:

@Override  
public View getView(int position, View convertView, ViewGroup parent) {  
    if (convertView == null) {  
        convertView = LayoutInflater.from(context).inflate(  
                R.layout.list_item, parent, false);  
    }     

    return convertView;  
}  
 
 
 
         
  • 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中改為:

layout=(LinearLayout)findViewById(R.id.layout1); 
View view=LayoutInflater.from(this).inflate(R.layout.list_item,layout , false); 
        layout.addView(view); 
 
 
 
         
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

最終運行效果會發現 
android:layout_height, android:layout_margin都已經有效果了。







免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM