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

Android 仿 iOS UIAlertView 對話框

編輯:關於 Android 程式設計

顯示效果

我在參考連結中看到原作者仿的 QQ 提示框,但实际使用起來並不太順手,有一些不足之處。於是我參照系統的 AlertDialog 設計,沿用參考連結中的布局檔與 style 檔,用自己的方式重新封裝成一個仿 iOS UIAlertView 效果的 CustomDialog,讓我們可以像使用系統 AlertDialog 一樣自然地使用它。

使用方式

最大的賣點是:API 幾乎與 AlertDialog.Builder 一致,換掉類別名稱就能遷移。

package com.example.iosalertview;

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;
import com.example.iosalertview.CustomDialog.Builder;

public class MainActivity extends Activity implements OnClickListener {

    private Button ios_dialog_btn, android_dialog_btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ios_dialog_btn = (Button) findViewById(R.id.ios_dialog_btn);
        android_dialog_btn = (Button) findViewById(R.id.android_dialog_btn);
        ios_dialog_btn.setOnClickListener(this);
        android_dialog_btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ios_dialog_btn:
                CustomDialog.Builder builder = new Builder(MainActivity.this);
                builder.setTitle(R.string.prompt);
                builder.setMessage(R.string.exit_app);
                builder.setPositiveButton(R.string.confirm, null);
                builder.setNegativeButton(R.string.cancel, null);
                builder.create().show();
                break;

            case R.id.android_dialog_btn:
                AlertDialog.Builder mbuilder = new AlertDialog.Builder(MainActivity.this);
                mbuilder.setTitle(R.string.prompt);
                mbuilder.setMessage(R.string.exit_app);
                mbuilder.setPositiveButton(R.string.confirm, null);
                mbuilder.setNegativeButton(R.string.cancel, null);
                mbuilder.create().show();
                break;

            default:
                break;
        }
    }
}

CustomDialog 實作

設計重點是:內部 Builder 模式封裝所有設定,create() 時才真正 inflate 布局並綁定監聽器。

package com.example.iosalertview;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CustomDialog extends Dialog {

    public CustomDialog(Context context) {
        super(context);
    }

    public CustomDialog(Context context, int theme) {
        super(context, theme);
    }

    public static class Builder {
        private Context context;
        private String title;              // 標題
        private String message;            // 內容
        private String confirm_btnText;    // 「確定」
        private String cancel_btnText;     // 「取消」
        private View contentView;          // 中間可換成自訂布局

        private DialogInterface.OnClickListener confirm_btnClickListener;
        private DialogInterface.OnClickListener cancel_btnClickListener;

        public Builder(Context context) {
            this.context = context;
        }

        public Builder setMessage(String message) {
            this.message = message;
            return this;
        }

        public Builder setMessage(int message) {
            this.message = (String) context.getText(message);
            return this;
        }

        public Builder setTitle(int title) {
            this.title = (String) context.getText(title);
            return this;
        }

        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }

        public Builder setContentView(View v) {
            this.contentView = v;
            return this;
        }

        public Builder setPositiveButton(int confirm_btnText,
                                         DialogInterface.OnClickListener listener) {
            this.confirm_btnText = (String) context.getText(confirm_btnText);
            this.confirm_btnClickListener = listener;
            return this;
        }

        public Builder setPositiveButton(String confirm_btnText,
                                         DialogInterface.OnClickListener listener) {
            this.confirm_btnText = confirm_btnText;
            this.confirm_btnClickListener = listener;
            return this;
        }

        public Builder setNegativeButton(int cancel_btnText,
                                         DialogInterface.OnClickListener listener) {
            this.cancel_btnText = (String) context.getText(cancel_btnText);
            this.cancel_btnClickListener = listener;
            return this;
        }

        public Builder setNegativeButton(String cancel_btnText,
                                         DialogInterface.OnClickListener listener) {
            this.cancel_btnText = cancel_btnText;
            this.cancel_btnClickListener = listener;
            return this;
        }

        public CustomDialog create() {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            // 用自訂主題建立 dialog
            final CustomDialog dialog = new CustomDialog(context, R.style.mystyle);
            View layout = inflater.inflate(R.layout.customdialog, null);
            dialog.addContentView(layout, new LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

            // 標題
            ((TextView) layout.findViewById(R.id.title)).setText(title);
            ((TextView) layout.findViewById(R.id.title)).getPaint().setFakeBoldText(true);

            // 確定鈕
            if (confirm_btnText != null) {
                ((Button) layout.findViewById(R.id.confirm_btn)).setText(confirm_btnText);
                if (confirm_btnClickListener != null) {
                    ((Button) layout.findViewById(R.id.confirm_btn))
                            .setOnClickListener(new View.OnClickListener() {
                                public void onClick(View v) {
                                    confirm_btnClickListener.onClick(
                                            dialog, DialogInterface.BUTTON_POSITIVE);
                                }
                            });
                }
            } else {
                // 沒有就隱藏
                layout.findViewById(R.id.confirm_btn).setVisibility(View.GONE);
            }

            // 取消鈕
            if (cancel_btnText != null) {
                ((Button) layout.findViewById(R.id.cancel_btn)).setText(cancel_btnText);
                if (cancel_btnClickListener != null) {
                    ((Button) layout.findViewById(R.id.cancel_btn))
                            .setOnClickListener(new View.OnClickListener() {
                                public void onClick(View v) {
                                    cancel_btnClickListener.onClick(
                                            dialog, DialogInterface.BUTTON_NEGATIVE);
                                }
                            });
                }
            } else {
                layout.findViewById(R.id.cancel_btn).setVisibility(View.GONE);
            }

            // 內容:文字或自訂 View 二擇一
            if (message != null) {
                ((TextView) layout.findViewById(R.id.message)).setText(message);
            } else if (contentView != null) {
                LinearLayout container =
                        (LinearLayout) layout.findViewById(R.id.message);
                container.removeAllViews();
                container.addView(contentView, new LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            }

            dialog.setContentView(layout);
            return dialog;
        }
    }
}

Demo 下載

原始範例與資源檔可參考作者發佈的 CSDN 下載頁。

參考連結

https://www.apkbus.com/forum.php?mod=viewthread&tid=160284

如果要用在今天的專案上

這個實作寫於 AlertDialog 客製化還很麻煩的年代,作為 Builder 模式的練習很合適。但在新專案中建議改用 DialogFragment(或 androidx 的 DialogFragment),原因有三:它會隨 FragmentManager 一起管理生命週期,旋轉螢幕不會導致視窗洩漏;它天生避開了「Activity 已銷毀卻仍持有 Dialog」造成的 BadTokenException 與 window leak;此外樣式可以直接寫在 XML 裡,不必用程式動態 inflate。上面這份程式碼中「Builder 只收集設定、create() 才綁定監聽器」的思路,在 DialogFragment 裡同樣適用。

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