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

Android 自定義對話框:AlertDialog 搭配自訂版面

編輯:關於 Android 程式設計

系統預設的 AlertDialog 只有標題、訊息與按鈕,一旦需要在對話框裡放輸入框或其他元件,就得自己指定版面。做法其實很單純:先寫一個版面檔,再用 LayoutInflater 填載,最後透過 AlertDialog.Builder 的 setView() 指定。

一、自訂版面

先準備一個版面檔(此例為 home_phone.xml),裡面放兩個 EditText,分別用來輸入名稱與電話:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp">

    <EditText
        android:id="@+id/alert_homephone_nameEt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="名稱" />

    <EditText
        android:id="@+id/alert_homephone_phoneEt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="電話"
        android:inputType="phone" />

</LinearLayout>

這個版面就是對話框要顯示的內容。

二、在程式碼中填載並顯示

AlertDialog.Builder builder = new AlertDialog.Builder(this);

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.home_phone, null);
builder.setView(layout);

EditText homePhoneNameEt = (EditText) layout.findViewById(R.id.alert_homephone_nameEt);
EditText homePhoneEt = (EditText) layout.findViewById(R.id.alert_homephone_phoneEt);
homePhoneEt.setText("13195338922");
homePhoneNameEt.setText("老王");

builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        //在這裡取出 homePhoneNameEt 與 homePhoneEt 的內容做處理
    }
});

builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
    }
});

builder.show();

注意最後別忘了呼叫 show(),否則對話框不會出現。

三、重點整理

整個流程就是:自訂一個 layout → 用 LayoutInflater 填載 → 交給 AlertDialog.Builder 的 setView() → 呼叫 show()。

關於 show(),官方 API 的說明是:以 Builder 上設定的參數建立一個 AlertDialog,並呼叫 Dialog.show() 把它顯示出來。也就是「建立 + 顯示」一次完成。

實務上還有一個常被忽略的細節:在 setPositiveButton 的 onClick 裡直接讀取 EditText 的值是可以的,因為 view 已經被外部持有;但如果你希望使用者按確定後能攔截輸入內容不被關閉,就需要改用自訂 Dialog 並覆寫 dispatchPopulateControls,這超出本篇範圍,有興趣可以再深入。

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