android LayoutInflater.inflate()的參數介紹


LayoutInflater.inflate()的作用就是將一個xml定義的布局文件實例化為view控件對象;

 

與findViewById區別:

 LayoutInflater.inflate是加載一個布局文件;

 findViewById則是從布局文件中查找一個控件;

 

一.獲取LayoutInflater對象有三種方法

LayoutInflater inflater=LayoutInflater.from(context);


LayoutInflater inflater=getLayoutInflater();在Activity中可以使用,實際上是View子類下window的一個函數


LayoutInflater inflater=(LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);

 

二:inflate 參數

public View inflate(int resource, ViewGroup root, boolean attachToRoot) :

reSource:View的layout的ID 
root:需要附加到resource資源文件的根控件,inflate()會返回一個View對象,如果第三個參數attachToRoot為true,就將這個root作為根對象返回,否則僅僅將這個root對象的LayoutParams屬性附加到resource對象的根布局對象上,也就是布局文件resource的最外層的View上。如果root為null則會忽略view根對象的LayoutParams屬性(注意)。

attachToRoot:是否將root附加到布局文件的根視圖上


例子:

LayoutInflater  inflater  = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.fragment, root,false);

或者:

v = inflater.inflate(R.layout.fragment, null);

 

常見問題:

有時候我們在Adapter加載自定義的view布局文件,布局文件中設置了android:layout_height="100dip",但是運行程序后發現一點作用都沒有,相似的還有layout_width等以android:layout_開頭的屬性設置都沒有作用;

因為Adapter里有一個方法是getView,這個返回的VIew是一個從XML布局里加載的,一般如下:

View v = inflater.inflate(R.layout.fragment, null);
 
問題恰恰出在我們的LayoutInflater.from(mContext).inflate(R.layout.main, null);這句代碼上,在使用inflate的時候,如果第二個參數(View root)為null,那么將不會加載你的布局文件里的最頂層的那個布局節點的布局相關配置(就是以android:layout_開頭的屬性)..我們可以看下該方法的實現來說明一下,通過查找源代碼,inflate的實現都在這個public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 方法里定義。。其中一段:
          if (root != null) {
                        if (DEBUG) {
                            System.out.println("Creating params from root: " +
                                    root);
                        }
                        // Create layout params that match root, if supplied
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }

代碼中可以發現:當root為null的時候是不會執行params = root.generateLayoutParams(attrs);這段代碼的,這段代碼就是把xml里的布局配置轉為LayoutParams,換句說就是加載我們配置的布局屬性,以供布局類(FrameLayout等)在onLayout的時候控制View的大小、位置、對齊等等。。以FrameLayout為例,看下它的generateLayoutParams(attrs)方法。
 
解決辦法:
 
使用LayoutInflate的inflate方法的時候一定要保證root參數不能為null,其實這個root就是父View的意思,就是說你把xml轉換為一個VIew的時候,該VIew的Parent是root,如果你不想把該View添加到該root里,那么讓第三個參數 attachToRoot為false,如果要添加則為true.
 

 


免責聲明!

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



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