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

LayoutInflater:把 XML 版面配置實例化為 View 物件

編輯:關於 Android 程式設計

LayoutInflater 的作用,是把 layout 的 XML 版面配置檔實例化成對應的 View 物件。當你想在程式執行時動態載入某個版面,就會用到它。

取得 LayoutInflater 的三種方式

// 方法一:透過系統服務
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.main, null);

// 方法二:透過靜態方法(本質等同方法一,可參考原始碼)
LayoutInflater inflater = LayoutInflater.from(context);
View layout = inflater.inflate(R.layout.main, null);

// 方法三:在 Activity 中直接呼叫(實際上是 Window 的方法)
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.main, null);

使用範例

比起直接 setContentView(R.layout.main),我們也可以先 inflate 出 View 再設定給 Activity,兩者效果相同:

public class MyInflate extends Activity {
    private TextView tv;

    public void OnCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.main);
        // tv = (TextView) findViewById(R.id.tv);

        LayoutInflater inflate = LayoutInflater.from(this);
        View view = inflate.inflate(R.layout.main, null);
        setContentView(view);
    }
}

掌握 LayoutInflater,就能在需要時靈活地把 XML 版面變成可自由操作、附加的 View 物件。

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