Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

用 LayoutInflater 動態載入版面並操作控制項

編輯:Android 開發實例

Android 通常以版面檔描述介面,並在 Activity 中以 setContentView() 把它顯示出來。但如果情境不在 Activity 之內——例如在自訂的 Adapter 裡——又想取得版面中的控制項進行設定,該怎麼辦?這時就需要 LayoutInflater。

準備一個簡單版面 example.xml

<TextView
    android:id="@+id/tview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="FENGFLY.COM"
/>
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:text="按鈕"
/>

在程式中動態載入

LayoutInflater flater = LayoutInflater.from(this);
View view = flater.inflate(R.layout.example, null);

inflate() 的回傳值是一個 View 物件,代表整棵版面樹的節點,後續所有操作都從它出發。

取得版面中的控制項

button = (Button) view.findViewById(R.id.button);
textView = (TextView) view.findViewById(R.id.tview);

掛上事件監聽

button.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
        textView.setText("WWW.FENGFLY.COM");
    }
});

實務提醒

LayoutInflater 最常出現的地方就是 Adapter 與 RecyclerView.ViewHolder 的實作中:先為項目版面建立 View,再對其中的控制項做資料綁定。兩個常見陷阱值得注意。

第一,inflate() 的第二與第三個參數決定版面參數如何處理。在 ListView 的 getView() 中,正確寫法是 inflate(R.layout.item, parent, false)——傳 true 會把 view 直接掛到 parent 上,導致控制項被重複附加而引發例外;而傳 null 則會讓根節點的 LayoutParams 遺失,造成版面錯位。

第二,findViewById() 必須從 inflate 出來的 view 呼叫,而不是從 Activity 呼叫,否則在項目版型中會取到錯誤的實例。列表滾動時也建議實作 ViewHolder 模式快取控制項參考,避免每次 bind 都重複搜尋而拖慢滾動流暢度。

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