Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android LayoutInflater 详解與使用方式

編輯:關於 Android 程式設計

作用:LayoutInflater 的作用類似於 findViewById(),兩者的不同點在於:LayoutInflater 是用來找 res/layout/ 下的 XML 版面配置檔並將其實例化;而 findViewById() 是找 XML 版面配置檔下的具體 widget 控制項(如 Button、TextView 等)。

具體作用如下:

1、對於一個未被載入或想要動態載入的界面,需要使用 LayoutInflater.inflate() 來載入;

2、對於一個已載入的界面,則可使用 Activity.findViewById() 方法取得其中的界面元素。

使用方式:

LayoutInflater 是一個抽象類別,取得其實例有三種方式:

// 1. 呼叫 Activity 的 getLayoutInflater()
LayoutInflater inflater = getLayoutInflater();
// 2. 透過 LayoutInflater.from(context)
LayoutInflater inflater = LayoutInflater.from(context);
// 3. 透過 getSystemService
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

inflate 方法有幾種多載形式,回傳值均為 View 物件:

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)

示意程式碼:

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom, (ViewGroup) findViewById(R.id.test));
// 注意:要從 inflate 後的 view 取得子元件,而非直接 findViewById
EditText editText = (EditText) view.findViewById(R.id.content);

上述程式碼指定了第二個參數 ViewGroup root,當然也可以設為 null。以下整理 getSystemService() 常見參數的種類:

WINDOW_SERVICE:WindowManager,管理開啟的視窗程式。

LAYOUT_INFLATER_SERVICE:LayoutInflater,取得 XML 裡定義的 view。

ACTIVITY_SERVICE:ActivityManager,管理應用程式的系統狀態。

POWER_SERVICE:PowerManager,電源服務。

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:TelephonyManager,電話服務。

Code Demo:

Context mContext = MainActivity.this;
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);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved