Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 開發筆記:LayoutInflater 與 inflate 方法用法整理

Activity 建立時執行的 onCreate 裡,最常見的一句莫過於:

public void OnCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

這是最簡單的布局載入方式。但如果你需要「動態」載入布局,就得換用另一條路——LayoutInflater 的 inflate 方法。

取得 LayoutInflater 的三種寫法

// 1. 直接呼叫 Activity 的方法
LayoutInflater inflater = getLayoutInflater();

// 2. 透過系統服務取得
LayoutInflater localInflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

// 3. 用靜態工廠方法
LayoutInflater inflater = LayoutInflater.from(context);

inflate 方法

public View inflate(int resource, ViewGroup root)

作用:依指定的 XML 資源檔,填充出一個新的視圖層級結構。

  • resource:View 布局的 ID
  • root:產生物件層級結構的根視圖
  • 回傳值:填充後層級結構的根視圖

如果傳入了 root,root 就是根視圖;若傳 null,則以 XML 檔案本身的根節點作為根視圖。其他幾個重載版本行為類似。另外,View 類別本身也有一個 inflate 方法,可一併參考。

等價寫法

下面這段其實和 setContentView(R.layout.main) 是同一件事,只是把過程攤開來寫:

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

把這三行與一行版的對照看過,動態載入布局就沒有祕密了:一切都在 inflate 這一步完成。

Copyright © Linux教程網 All Rights Reserved