【android】LayoutInflater.inflate方法的詳解及xml根項目的布局參數不起作用的問題

來源:互聯網
上載者:User

標籤: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根項目的布局參數不起作用的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.