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

Android 中 LayoutInflater 的作用與使用方式

編輯:關於 Android 開發

在實際開發中,LayoutInflater 是個相當實用的類別。它的作用有點類似 findViewById(),但兩者分工不同:LayoutInflater 找的是 layout 下的 XML 版面檔並將其實例化,而 findViewById() 找的是某個 XML 裡的具體 widget 控制項(如 Button、TextView)。一句話概括:LayoutInflater 負責把 XML 變成 View 物件樹,findViewById 負責在已有的 View 樹裡撈出特定節點。

下面做一個簡單的 Demo:主版面 main.xml 裡有一個 TextView 和一個 Button;點擊 Button 後彈出一個 Dialog,而這個 Dialog 的版面用的是我們自己在 layout 目錄下定義的 custom_dialog.xml(左右分布,左邊 ImageView、右邊 TextView)。

實作步驟

1. 新建一個Android專案,命名為 LayoutInflaterDemo。

2. 修改 main.xml,在原本的 TextView 之外加上一個 Button:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ShowCustomDialog"
        />
</LinearLayout>

3. 在 Button 的點擊事件裡,透過 LayoutInflater.from(this).inflate(R.layout.custom_dialog, null) 取得 custom_dialog 的 View,再把它設為 Dialog 的內容檢視即可。

兩個實務細節

inflate 的第二個參數不要習慣性寫 null 以外的東西而不思考。inflate(resource, root) 中的 root 決定要不要把生成的 View 掛到父容器上、以及版面參數(LayoutParams)由誰決定。建立 Dialog 內容時 root 通常傳 null,因為 Dialog 會自己接管;但若是要把一塊 View 動態插入既有的 LinearLayout,就該傳入該容器並讓 attachToRoot 為 true,否則 LayoutParams 會全部失效,寬高變成預設值。

LayoutInflater 了三個取得方式。LayoutInflater.from(context) 最常用;Activity 本身也有 getLayoutInflater();系統另有 Context.getSystemService(LAYOUT_INFLATER_SERVICE)。三者本質相同,挑順手的即可。

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