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

自訂 Dialog 入門:樣式、版面與互動的三段式做法

編輯:關於 Android 程式設計

系統 AlertDialog 的樣式很難改到符合設計稿,實務上幾乎都會走向自訂 Dialog。整個流程只有三段:寫版面、定義 Style、在需要的地方组装並顯示。

一、版面配置

以一個「登入狀態失效」提示框為例,包含標題、內容、分隔線與兩個並排按鈕。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/widget_margin_15"
        android:text="下線通知"
        android:textColor="@color/blue_0"
        android:textSize="@dimen/font_size_18" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/blue_0" />

    <TextView
        android:id="@+id/token_err"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/widget_margin_10"
        android:textColor="@color/black"
        android:textSize="@dimen/font_size_16" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/list_split_line_color" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/pop_exit"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@color/white"
            android:paddingTop="@dimen/widget_margin_15"
            android:paddingBottom="@dimen/widget_margin_15"
            android:text="退出"
            android:textColor="#0000ff"
            android:textSize="@dimen/font_size_18" />

        <View
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="@color/list_split_line_color" />

        <Button
            android:id="@+id/pop_relogin"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@color/white"
            android:paddingTop="@dimen/widget_margin_15"
            android:paddingBottom="@dimen/widget_margin_15"
            android:text="重新登陸"
            android:textColor="#0000ff"
            android:textSize="@dimen/font_size_18" />
    </LinearLayout>
</LinearLayout>

二、定義 Style

繼承系統的 Theme.Dialog,再逐步剝掉不需要的裝飾。

<style name="tokenDialog" parent="@android:style/Theme.Dialog">
    <item name="android:layout_marginLeft">10dp</item>
    <item name="android:layout_marginRight">10dp</item>
    <item name="android:windowNoTitle">true</item>
    <!-- 背景透明:讓左右留白處不會出現黑邊 -->
    <item name="android:windowBackground">@color/transparent</item>
</style>

windowNoTitle 拿掉預設標題列(標題改由版面自繪),windowBackground 設為透明則是為了避免自訂的左右 margin 之外露出系統預設的深色底。

三、組裝並顯示

/**
 * 登入資訊過期時顯示提示彈窗
 */
private static void initErrDialog(final Context ctx) {
    final Dialog dialog = new Dialog(ctx, R.style.tokenDialog);
    dialog.getWindow().setGravity(Gravity.CENTER);
    dialog.setCanceledOnTouchOutside(false);   // 點外部不關閉,強制使用者做選擇

    View view = LayoutInflater.from(ctx).inflate(R.layout.pop_token_outofdate_tips, null);
    Button exitBtn    = view.findViewById(R.id.pop_exit);
    Button reloginBtn = view.findViewById(R.id.pop_relogin);
    TextView errTxt   = view.findViewById(R.id.token_err);

    String time = new SimpleDateFormat("HH:mm", Locale.getDefault())
                      .format(new Date(System.currentTimeMillis()));
    errTxt.setText(Html.fromHtml(
        "您的賬號於 " + time + " 在另一部手機登錄。如非本人操作,則密碼可能已洩露,"
        + "建議前往 https://www.example.com 修改密碼。"));

    exitBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
            android.os.Process.killProcess(android.os.Process.myPid());  // 結束應用
        }
    });

    reloginBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
            TabMainActivity.getInst().finish();   // 不 finish 回來還會看到這個框
            TabMainActivity.getInst().startActivity(
                new Intent(TabMainActivity.getInst(), LoginActivity.class));
        }
    });

    dialog.setContentView(view);
    dialog.show();
}

四、實務上的幾個關鍵點

• 用 static 方法包起來,把 Dialog 的建立細節收在工具類中,呼叫端一行搞定。但要小心:static 方法持有 Activity 的短暫引用尚可,若把 Dialog 存成 static 欄位就是標準的記憶體洩漏寫法。
• Activity 銷毀前必須 dismiss。否則會拋 WindowLeaked(俗稱「洩漏視窗」)。最穩妥的做法是在 Activity 的 onDestroy 中判斷並 dismiss,或使用 DialogFragment 讓 FragmentManager 代管生命週期。
• 重新登入流程要 finish 原 Activity。範例中若不 finish 主畫面,返回鍵就會回到舊狀態,甚至再看到同一個彈窗。
• killProcess 是下策。直接殺進程在系統看來等同崩潰,可能影響 ANR 統計與推送重連。優雅做法是登出後清空返回堆疊(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_NEW_TASK)並導向登入頁。
• 若minSdk ≥ 17,findViewById 可直接寫成 view.findViewById() 的泛型推斷形式,省去轉型。

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