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

Android LayoutInflater 使用詳解

編輯:關於 Android 程式設計

在實際開發中,LayoutInflater 這個類別非常有用,它的作用有點類似 findViewById()。兩者的不同在於:LayoutInflater 是用來找 res/layout/ 底下的 XML 佈局檔並將其實例化;而 findViewById() 則是找 XML 佈局檔下的具體 widget 控件(如 Button、TextView 等)。

具體作用

LayoutInflater 主要用在兩種情境:第一,對於一個尚未被加載、或想要動態加載的介面,需要使用 LayoutInflater.inflate() 來加載;第二,對於一個已經加載的介面,則可以用 Activity.findViewById() 方法來取得其中的介面元素。

LayoutInflater 是一個抽象類別,在文檔中宣告為 public abstract class LayoutInflater extends Object。

獲得 LayoutInflater 實例的三種方式

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(),而在 PhoneWindow 的建構子中,可以看到 mLayoutInflater = LayoutInflater.from(context),也就是說它最終還是回到了 LayoutInflater.from(context)。

再看 LayoutInflater.from(context):它的實作是透過 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) 取得 LayoutInflater 服務物件,若取不到則丟出 AssertionError。

由此可見,無論你用哪一種寫法,最終取得的都是同一個由系統管理的 LayoutInflater 實例。理解這一點後,你就能依當下的上下文情境,自由地選擇最合適的寫法來加載佈局了。

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