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

Android 開發:取得 LayoutInflater 的四種常見寫法

編輯:關於 Android 程式設計

寫 Android 的時候,只要需要自訂 View,或者想在程式碼裡動態把一張 XML 佈局「吹」成真正的 View 物件,就繞不開 LayoutInflater。它像一台充氣機,把資源檔裡的標籤充氣成有生命、可互動的控制項。本文把取得這個物件的幾種常見寫法整理在一起,並順著原始碼把它們之間的關係串起來。

一、手上已經有 Context

最直覺的方式,是把它當成一項系統服務來取:

 LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View child = inflater.inflate(R.layout.child, null); 

如果不喜歡記那串長得沒道理的常數,也可以走 LayoutInflater.from() 這個捷徑:

 LayoutInflater inflater = LayoutInflater.from(context); View child = inflater.inflate(R.layout.child, null); 

二、身處 Activity 之中

Activity 本身預設就提供了取得管道:

 View child = getLayoutInflater().inflate(R.layout.child, item, false); 

當然,也可以先取得 Context 再走系統服務,效果完全相同:

 View view; LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.mylayout, null); 

仔細對照就會發現,方法一與方法二並沒有本質差異,後者同樣是 getSystemService() 的呼叫,只是換了一條取得 Context 的路徑。

三、借 View 的靜態方法

還有一種更精簡的寫法,直接把工作交給 View:

 View view = View.inflate(context, R.layout.child, null); 

翻開它的原始碼,語意一目了然:

 /** * Inflate a view from an XML resource. This convenience method wraps the {@link * LayoutInflater} class, which provides a full range of options for view inflation. * * @param context The Context object for your activity or application. * @param resource The resource ID to inflate * @param root A view group that will be the parent. Used to properly inflate the * layout_* parameters. * @see LayoutInflater */ public static View inflate(Context context, int resource, ViewGroup root) { LayoutInflater factory = LayoutInflater.from(context); return factory.inflate(resource, root); } 

而 LayoutInflater.from(context) 其實也只是方法一的包裝:

 /** * Obtains the LayoutInflater from the given 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.LAYOUT_INFLATER_SERVICE)。選哪一種,取決於你手上握有什麼——有 Context 就用 from(),在 Activity 裡就用 getLayoutInflater(),只想一行搞定就用 View.inflate()。

另外提醒一個常被忽略的細節:inflate() 的第二個參數 root 若傳入 null,佈局檔裡寫的 layout_width、layout_height 等 LayoutParams 屬性不會被套用。在為 ListView 產生單一項目時這通常是刻意的選擇,但在一般情境下可能造成尺寸不如預期,值得留意。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved