LayoutInflater介紹及例子


主要是利用LayoutInflater的inflate方法

 

相當於findViewById,只不過查找的是layout的資源

 

LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

linearLayout1 = (LinearLayout) mLayoutInflater.inflate(R.layout.main, null);

linearLayout2 = (LinearLayout) mLayoutInflater.inflate(R.layout.main2, null);

 

再通過檢測動作,執行setContentView(layout),可以完成切換

Android - LayoutInflater

   

實際開發中LayoutInflater這個類還是非常有用的,它的作用類似於findViewById()。不同點是LayoutInflater是用來找res/layout/下的xml布局文件,並且實例化;而 findViewById()是找xml布局文件下的具體widget控件(如Button、TextView等)。
具體作用:
1、對於一個沒有被載入或者想要動態載入的界面,都需要使用LayoutInflater.inflate()來載入;

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


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

public abstract class LayoutInflater extends Object  

 

獲得 LayoutInflater 實例的三種方式

1. LayoutInflater inflater = getLayoutInflater();  //調用Activity的getLayoutInflater()

2. LayoutInflater localinflater =  (LayoutInflater)context.getSystemService

                                                 (Context.LAYOUT_INFLATER_SERVICE);

3. LayoutInflater inflater = LayoutInflater.from(context);   

 

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

getLayoutInflater():

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

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

可以看出它其實是調用 LayoutInflater.from(context)。

 

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. public View inflate (XmlPullParser parser, ViewGroup root)  
  3.   
  4. public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)  
  5.   
  6. public View inflate (int resource, ViewGroup root, boolean attachToRoot)  

示意代碼:

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

對於上面代碼,指定了第二個參數 ViewGroup root,當然你也可以設置為 null 值。


注意:

·inflate 方法與 findViewById 方法不同;

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

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


Inflater英文意思是膨脹,在Android中應該是擴展的意思吧。 

LayoutInflater 的作用類似於 findViewById(),不同點是LayoutInflater是用來找layout文件夾下的xml布局文件,並且實例化!而 findViewById()是找具體某一個xml下的具體 widget控件(如:Button,TextView等)。

她可以有很多地方可以使用,如BaseAdapter的getView中,自定義Dialog中取得view中的組件widget等等。
它的用法有2種:

Java代碼
  1. view plaincopy to clipboardprint?  
  2. LayoutInflater inflater = LayoutInflater.from(this);     
  3. View view=inflater.inflate(R.layout.ID, null);    
  4. 或者干脆並成一句:    
  5. View view=LayoutInflater.from(this).inflate(R.layout.ID, null);    



另一種方法: 

Java代碼
  1. view plaincopy to clipboardprint?  
  2. LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);    
  3. View view=inflater.inflate(R.layout.ID, null);    
上面2種方法本質上是一樣的,看下面的源碼,form()調用的就是getSystemService(): 
Java代碼
  1. Java代碼  
  2. public static LayoutInflater from(Context context) {       
  3.     LayoutInflater LayoutInflater =       
  4.             (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);       
  5.     if (LayoutInflater == null) {       
  6.         throw new AssertionError("LayoutInflater not found.");       
  7.     }       
  8.     return LayoutInflater;       
  9. }     
另外getSystemService()是Android很重要的一個API,它是Activity的一個方法,根據傳入的NAME來取得對應的Object,然后轉換成相應的服務對象。以下介紹系統相應的服務。 

傳入的Name 返回的對象 說明
WINDOW_SERVICE WindowManager 管理打開的窗口程序
LAYOUT_INFLATER_SERVICE LayoutInflater 取得xml里定義的view
ACTIVITY_SERVICE ActivityManager 管理應用程序的系統狀態
POWER_SERVICE PowerManger 電源的服務
ALARM_SERVICE AlarmManager 鬧鍾的服務
NOTIFICATION_SERVICE NotificationManager 狀態欄的服務
KEYGUARD_SERVICE KeyguardManager 鍵盤鎖的服務
LOCATION_SERVICE LocationManager 位置的服務,如GPS
SEARCH_SERVICE SearchManager 搜索的服務
VEBRATOR_SERVICE Vebrator 手機震動的服務
CONNECTIVITY_SERVICE Connectivity 網絡連接的服務
WIFI_SERVICE WifiManager Wi-Fi服務
TELEPHONY_SERVICE TeleponyManager 電話服務


Java代碼
  1. Java代碼  
  2. //基本用法    
  3. public void showCustomDialog(){    
  4.   AlertDialog.Builder builder;    
  5.   AlertDialog alertDialog;    
  6.   Context mContext = AppActivity.this;    
  7. //下面倆種方法都可以    
  8.   //LayoutInflater inflater = getLayoutInflater();    
  9.   LayoutInflater inflater = (LayoutInflater)     
  10. mContext.getSystemService(LAYOUT_INFLATER_SERVICE);    
  11.   View layout = inflater.inflate(R.layout.custom_dialog,null);    
  12.   TextView text = (TextView) layout.findViewById(R.id.text);    
  13.   text.setText("Hello, Welcome to Mr Wei's blog!");    
  14.   ImageView image = (ImageView) layout.findViewById(R.id.image);    
  15.   image.setImageResource(R.drawable.icon);    
  16.   builder = new AlertDialog.Builder(mContext);    
  17.   builder.setView(layout);    
  18.   alertDialog = builder.create();    
  19.   alertDialog.show();    
  20.  }    
  21. }    
  22.     
  23. protected void showToast(int type) {      
  24.         Toast.makeText(this"*********", Toast.LENGTH_LONG).show();      
  25.       
  26.         LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);      
  27.         View view = li.inflate(R.layout.toast, null);      
  28.               
  29.         Toast toast = new Toast(this);      
  30.         toast.setView(view);      
  31.         toast.setDuration(type);      
  32.         toast.show();      
  33.     }  
    例子

在實際開發中LayoutInflater這個類還是非常有用的,它的作用類似於findViewById(),不同的是LayoutInflater是用來找layout下xml布局文件,並且實例化!而findViewById()是找具體xml下的具體widget控件(如:Button,TextView等)。

為了讓大家更容易理解我做了一個簡單的Demo,主布局main.xml里有一個TextView和一個Button,當點擊Button,出現Dialog,而這個Dialog的布局方式是我們在layout目錄下定義的custom_dialog.xml文件(里面左右分布,左邊ImageView,右邊TextView)。

效果圖如下:

LayoutInflaterDemo

下面我將詳細的說明Demo的實現過程:

1、新建一個Android工程,我們命名為LayoutInflaterDemo.

2、修改main.xml布局,里面主要在原來基礎上增加了一個Button.代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<? xml version = "1.0" encoding = "utf-8" ?>
< LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
     android:orientation = "vertical"
     android:layout_width = "fill_parent"
     android:layout_height = "fill_parent" >
     < TextView
         android:layout_width = "fill_parent"
         android:layout_height = "wrap_content"
         android:text = "@string/hello" />
     < Button
         android:id = "@+id/button"
         android:layout_width = "wrap_content"
         android:layout_height = "wrap_content"
         android:text = "ShowCustomDialog" />
</ LinearLayout >

3、定義對話框的布局方式,我們在layout目錄下,新建一個名為custom_dialog.xml文件,具體代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<? xml version = "1.0" encoding = "utf-8" ?>
< LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
     android:orientation = "horizontal"
     android:layout_width = "fill_parent"
     android:layout_height = "fill_parent"
     android:padding = "10dp" >
     < ImageView
         android:id = "@+id/image"
         android:layout_width = "wrap_content"
         android:layout_height = "fill_parent"
         android:layout_marginRight = "10dp" />
     < TextView
         android:id = "@+id/text"
         android:layout_width = "wrap_content"
         android:layout_height = "fill_parent"
         android:textColor = "#FFF" />
</ LinearLayout >

4、修改主程序LayouInflaterDemo.java代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.android.tutor;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
 
public class LayoutInflaterDemo extends Activity implements OnClickListener {
 
     private Button button;
 
     public void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.main);
 
         button = (Button) findViewById(R.id.button);
         button.setOnClickListener( this );
     }
 
     @Override
     public void onClick(View v) {
 
         showCustomDialog();
     }
 
     public void showCustomDialog() {
         AlertDialog.Builder builder;
         AlertDialog alertDialog;
         Context mContext = LayoutInflaterDemo. this ;
 
         // 下面倆種方法都可以
         // //LayoutInflater inflater = getLayoutInflater();
         LayoutInflater inflater = (LayoutInflater) mContext
                 .getSystemService(LAYOUT_INFLATER_SERVICE);
         View layout = inflater.inflate(R.layout.custom_dialog, null );
         TextView text = (TextView) layout.findViewById(R.id.text);
         text.setText( "Hello, Welcome to Mr Wei's blog!" );
         ImageView image = (ImageView) layout.findViewById(R.id.image);
         image.setImageResource(R.drawable.icon);
         builder = new AlertDialog.Builder(mContext);
         builder.setView(layout);
         alertDialog = builder.create();
         alertDialog.show();
     }
}

5、最后執行,點擊Button,將得到上述效果。

 

 

2-------------------------------------------------------------------------------------------------------------------------

實際開發中LayoutInflater這個類還是非常有用的,它的作用類似於findViewById()。不同點是LayoutInflater是用來找res/layout/下的xml布局文件,並且實例化;而findViewById()是找xml布局文件下的具體widget控件(如Button、TextView等)。
具體作用:
1、對於一個沒有被載入或者想要動態載入的界面,都需要使用LayoutInflater.inflate()來載入;
2、對於一個已經載入的界面,就可以使用Activiyt.findViewById()方法來獲得其中的界面元素。
LayoutInflater 是一個抽象類,在文檔中如下聲明:
public abstract class LayoutInflater extends Object
獲得 LayoutInflater 實例的三種方式

1
2
3
4
1 . LayoutInflater inflater = getLayoutInflater(); //調用Activity的getLayoutInflater() 
2 . LayoutInflater inflater = LayoutInflater.from(context);  
3 . LayoutInflater inflater =  (LayoutInflater)context.getSystemService
                               (Context.LAYOUT_INFLATER_SERVICE);

 

其實,這三種方式本質是相同的,從源碼中可以看出:
getLayoutInflater():
Activity 的 getLayoutInflater() 方法是調用 PhoneWindow 的getLayoutInflater()方法,看一下該源代碼

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

可以看出它其實是調用 LayoutInflater.from(context)。
LayoutInflater.from(context):

1
2
3
4
5
6
7
8
9
10
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()。
另外getSystemService()是Android很重要的一個API,它是Activity的一個方法,根據傳入的NAME來取得對應的Object,然后轉換成相應的服務對象。以下介紹系統相應的服務。
 

傳入的Name  返回的對象 說明
WINDOW_SERVICE WindowManager 管理打開的窗口程序
LAYOUT_INFLATER_SERVICE LayoutInflater 取得xml里定義的view
ACTIVITY_SERVICE ActivityManager 管理應用程序的系統狀態
POWER_SERVICE PowerManger 電源的服務
ALARM_SERVICE AlarmManager 鬧鍾的服務
NOTIFICATION_SERVICE NotificationManager 狀態欄的服務
KEYGUARD_SERVICE KeyguardManager 鍵盤鎖的服務
LOCATION_SERVICE LocationManager 位置的服務,如GPS
SEARCH_SERVICE SearchManager 搜索的服務
VEBRATOR_SERVICE Vebrator 手機震動的服務
CONNECTIVITY_SERVICE Connectivity 網絡連接的服務
WIFI_SERVICE WifiManager Wi-Fi服務
TELEPHONY_SERVICE TeleponyManager 電話服務

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

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

示意代碼:

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

對於上面代碼,指定了第二個參數 ViewGroup root,當然你也可以設置為 null 值。

注意:
·inflate 方法與 findViewById 方法不同;
·inflater 是用來找 res/layout 下的 xml 布局文件,並且實例化;
·findViewById() 是找具體 xml 布局文件中的具體 widget 控件(如:Button、TextView 等)。


免責聲明!

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



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