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

Android 建立 AlertDialog 對話框的最小實作

編輯:關於 Android 程式設計

提示訊息、二次確認、簡單表單,這些都是對話框的常見用途。Android 內建的 AlertDialog.Builder 用串接(chain)的方式設定屬性,寫起來相當直覺。本文用一個最小可運行的例子說明。

版面配置

這裡只放一顆按鈕,點下去就彈出對話框:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</RelativeLayout>

Activity 程式碼

package com.akwolf.android;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DialogActivity extends Activity {

    private Button dialogBtn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        dialogBtn = (Button) findViewById(R.id.button1);
        dialogBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(DialogActivity.this)
                        .setIcon(R.drawable.icon)
                        .setTitle("Infomation")
                        .setMessage("Hello World")
                        .setPositiveButton("確定", null)
                        .setNegativeButton("取消", null)
                        .show();
            }
        });
    }
}

Builder 常用方法整理

除了最基本的 setIcon / setTitle / setMessage,Builder 還提供不少實用選項:

  • setPositiveButton / setNegativeButton / setNeutralButton:最多三顆按鈕,第二個參數是點擊監聽器。
  • setCancelable(false):禁止使用者按返回鍵關閉,適合強制確認的場景。
  • setItems 或 setSingleChoiceItems:把對話框變成清單式選擇。
  • setView:塞入自訂版面,做出登入框、輸入框等效果。

小提醒:建立對話框的物件建議交給 Activity 的 Context(如本例的 this),傳 Application Context 會拿到錯誤的視窗權杖而拋出例外。另外,若在支援 Appcompat 的專案中,用 android.support.v7.app.AlertDialog 或 androidx.appcompat.app.AlertDialog 才能拿到一致的深色主題樣式。

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