android LayoutInflater.inflate()的參數介紹

LayoutInflater大家都用很久了,但是有時候有些小問題比如inflate出來的view屬性沒有生效等等都困擾着大家;又比如在自定義的adapter裏面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.
 



 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章