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

Android LayoutInflater 的用法與實作詳解

編輯:關於 Android 程式設計

在 Android 中,LayoutInflater 的作用有點類似於 Activity 的 findViewById(id),但兩者截然不同:LayoutInflater 是用來「找」並「實例化」一個 layout 下的 XML 佈局檔,而 findViewById 則是從既有佈局中「找」出具體的 widget 控制項(如 Button、TextView)。本文透過一個「點擊彈出自訂 Dialog」的例子來說明。

步驟一:建立 dialog.xml

在 res/layout 下新增一個描述 Dialog 內容的佈局檔:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <ImageView
        android:id="@+id/diaimage"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent" >
    </ImageView>
    <TextView
        android:id="@+id/diatv"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent" />
</LinearLayout>

步驟二:在 main.xml 加入觸發按鈕

<Button
    android:id="@+id/btnshowdialog"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Show Dialog" />

步驟三:在 MainActivity 中實作

透過 getLayoutInflater().inflate() 把 XML 佈局實例化成 View 物件,再將它設定為 Dialog 的內容:

Button showdialog = (Button) findViewById(R.id.btnshowdialog);
showdialog.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.dialog, null); // 把 XML 實例化為 View

        TextView diatv = (TextView) layout.findViewById(R.id.diatv);
        diatv.setText("Welcome to LayoutInflater study");
        ImageView image = (ImageView) layout.findViewById(R.id.diaimage);
        image.setImageResource(R.drawable.ic_launcher);

        builder.setView(layout); // 重點:將對話框內容設為這個 View
        AlertDialog dialog = builder.create();
        dialog.show();
    }
});

運行成果

點擊按鈕後,便會彈出一個內容為自訂佈局的 Dialog。透過這個範例,你已掌握 LayoutInflater 的核心用法:把靜態的 XML 佈局動態地「充氣」成可用的 View 物件。

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