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

Android 獲取 LayoutInflater 對象的幾種方法總結

編輯:關於 Android 程式設計

在編寫 Android 程序時,我們常常需要自定義 View,並用 Inflater 對象把布局文件解析成一個 View。本文就來總結一下獲取 LayoutInflater 對象的常見方法。

一、已持有 Context 對象時

可以通過系統服務獲取:

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

或者使用更簡潔的靜態工廠方法:

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

二、在 Activity 中

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

或者:

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

其實方法一和方法二本質上都是對 context.getSystemService() 的使用。

三、使用 View 的靜態方法

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

其源碼如下:

public static View inflate(Context context, int resource, ViewGroup root) {
    LayoutInflater factory = LayoutInflater.from(context);
    return factory.inflate(resource, root);
}

可以看到,View.inflate 內部其實就是調用了 LayoutInflater.from(context)。而 from 方法本身又只是對方法一的封裝:

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;
}

由此可見,這些看似不同的寫法,追根溯源都是圍繞 getSystemService(LAYOUT_INFLATER_SERVICE) 展開的,只是封裝層次和調用方式各異而已。

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