Android獲取LayoutInflater對象的方法總結

在寫Android程序時,有時候會編寫自定義的View,使用Inflater對象來將佈局文件解析成一個View。本文主要目的是總結獲取LayoutInflater對象的方法。


1、若能獲取context對象,可以有以下幾種方法:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  2. View child = inflater.inflate(R.layout.child, null);  

or

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. LayoutInflater inflater = LayoutInflater.from(context);  
  2. View child = inflater.inflate(R.layout.child, null);  
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. </pre><p></p><pre>  
2、在一個Activity中,可以有以下方法:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. View child = getLayoutInflater().inflate(R.layout.child, item, false);  
or

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. View view;   
  2. LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);   
  3. view = inflater.inflate(R.layout.mylayout, null);  

方法1和方法2其實都是對context().getSystemService()的使用


3、使用View的靜態方法:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. View view=View.inflate(context, R.layout.child, null)  

inflate實現源碼如下:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. /** 
  2.  * Inflate a view from an XML resource.  This convenience method wraps the {@link 
  3.  * LayoutInflater} class, which provides a full range of options for view inflation. 
  4.  * 
  5.  * @param context The Context object for your activity or application. 
  6.  * @param resource The resource ID to inflate 
  7.  * @param root A view group that will be the parent.  Used to properly inflate the 
  8.  * layout_* parameters. 
  9.  * @see LayoutInflater 
  10.  */  
  11. public static View inflate(Context context, int resource, ViewGroup root) {  
  12.     LayoutInflater factory = LayoutInflater.from(context);  
  13.     return factory.inflate(resource, root);  
  14. }  
LayoutInflater.from(context)實際上是對方法1的包裝,可參考以下源碼:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. /** 
  2.  * Obtains the LayoutInflater from the given context. 
  3.  */  
  4. public static LayoutInflater from(Context context) {  
  5.     LayoutInflater LayoutInflater =  
  6.             (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  7.     if (LayoutInflater == null) {  
  8.         throw new AssertionError("LayoutInflater not found.");  
  9.     }  
  10.     return LayoutInflater;  
  11. }  


發佈了7 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章