LayoutInflater的獲取與使用

在實際開發中LayoutInflater這個類仍是很是有用的,它的做用 相似於findViewById()。不一樣點是LayoutInflater是用來找res/layout/下的xml佈局文件,而且實例化;而 findViewById()是找xml佈局文件下的具體widget控件(如Button、TextView等)。
具體做用:
一、對於一個沒有被載入或者想要動態載入的界面,都須要使用LayoutInflater.inflate()來載入;html

二、對於一個已經載入的界面,就可使用Activiyt.findViewById()方法來得到其中的界面元素。api


LayoutInflater 是一個抽象類,在文檔中以下聲明:佈局

public abstract class LayoutInflater extends Object  spa

 

得到 LayoutInflater 實例的三種方式code

LayoutInflater inflater = getLayoutInflater();  //調用Activity的getLayoutInflater()LayoutInflater localinflater =  (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

LayoutInflater inflater = LayoutInflater.from(context);

 

其實,這三種方式本質是相同的,從源碼中能夠看出:xml

getLayoutInflater():htm

Activity 的 getLayoutInflater() 方法是調用 PhoneWindow 的getLayoutInflater()方法,看一下該源代碼:對象

 

複製代碼

1 public PhoneWindow(Context context) {  
2 3         super(context);  
4 5         mLayoutInflater = LayoutInflater.from(context);  
6 7 }

複製代碼

 

能夠看出它實際上是調用 LayoutInflater.from(context)。blog

 

LayoutInflater.from(context):開發

  • public static LayoutInflater from(Context context) {   

  •     LayoutInflater LayoutInflater =   

  •             (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);   

  •     if (LayoutInflater == null) {   

  •         throw new AssertionError("LayoutInflater not found.");   

  •     }   

  •     return LayoutInflater;   

能夠看出它其實調用 context.getSystemService()。

 

結論:因此這三種方式最終本質是都是調用的Context.getSystemService()。

 

inflate 方法
經過 sdk 的 api 文檔,能夠知道該方法有如下幾種過載形式,返回值均是 View 對象,以下:

 

複製代碼

1 public View inflate (int resource, ViewGroup root)  
2 3 public View inflate (XmlPullParser parser, ViewGroup root)  
4 5 public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)  
6 7 public View inflate (int resource, ViewGroup root, boolean attachToRoot)

複製代碼

 

示意代碼:

1 LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);  
2 View view = inflater.inflate(R.layout.custom, (ViewGroup)findViewById(R.id.test));  
3 4 //EditText editText = (EditText)findViewById(R.id.content);// error  5 6 EditText editText = (EditText)view.findViewById(R.id.content);

 

對於上面代碼,指定了第二個參數 ViewGroup root,固然你也能夠設置爲 null 值。


注意:

·inflate 方法與 findViewById 方法不一樣;

·inflater 是用來找 res/layout 下的 xml 佈局文件,而且實例化;

·findViewById() 是找具體 xml 佈局文件中的具體 widget 控件(如:Button、TextView 等)。

 

轉自 http://blog.sina.com.cn/s/blog_48a45b950100u8ax.html

相關文章
相關標籤/搜索