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

Android 三種對話框寫法總結:AlertDialog、Dialog 與 Activity 樣式視窗

編輯:關於 Android 程式設計

專案裡對話框的需求大致分三類:單純的確認提示、需要自訂版面的進度提示、以及需要輸入資料的表單。這三種對應三種不同的實作方式,本篇逐一整理。

一、AlertDialog:確認框

最常見的場景。搭配 AsyncTask 使用時,按下「是」才真的執行刪除動作:

AlertDialog.Builder builder = new Builder(HomeActivity.this);
builder.setTitle("提示");
builder.setMessage("是否刪除信息?");
builder.setPositiveButton("是", new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                if (mRejectLeaveInfoDao == null) {
                    mRejectLeaveInfoDao = new RejectLeaveInfosDao(HomeActivity.this);
                } else {
                    mRejectLeaveInfoDao.deleteLeaveInfo(tmpInfoReject);
                }
                fillDataReject();
                return null;
            }
        }.execute();
    }
});
builder.setNegativeButton("否", new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
    }
});
builder.create().show();

注意 doInBackground 裡才是真正做資料庫動作的環境;若把刪除寫在 onClick 裡直接執行,資料量一大就會造成 ANR。

二、Dialog:自訂版面的進度框

掃描、下載這類需要顯示進度又不想讓使用者亂按的場合,直接用 Dialog 換上自訂版面,並用 setCancelable(false) 禁掉返回鍵關閉:

new AsyncTask<Void, Object, Void>() {
    List<VirusApp> apps = new ArrayList<VirusApp>();
    String desc = null;
    Dialog dialog = new Dialog(KillVirusActivity.this);
    View viewKilling = View.inflate(KillVirusActivity.this, R.layout.killing_dialog, null);

    @Override
    protected void onPreExecute() {
        mKillVirusResult.setText("正在掃描中,請稍等...");
        dialog.setCancelable(false);
        dialog.setContentView(viewKilling);
        dialog.show();
    }
    // ...
};

對應的版面檔很簡單,一個 ProgressBar 加一行說明文字:

<?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="match_parent"
    android:orientation="vertical" >

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="病毒掃描中..."
        android:textSize="15sp" />
</LinearLayout>

三、Activity 樣式:需要輸入的表單

當對話框裡要放好幾個 EditText、需要鍵盤輸入並驗證時,Dialog 的版面會很難安排。更靈活的做法是「把 Activity 做成對話框的樣子」:去掉標題列與狀態列,讓它半透明地浮在上層。

public class AddKeyWordsInfosDailogActivity extends Activity {

    protected static final int ADD_KEY_INFO_SCUCESS = 100;

    private EditText et_key_words_input;   // 輸入關鍵字
    private EditText et_key_words_decribe;
    private Button mSure;                  // 確定
    private Button mCancel;                // 取消

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);            // 去除 title
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);      // 去掉狀態列
        setContentView(R.layout.add_keyword_info_activity);
        init();
        setListener();
    }

    private void setListener() {
        mSure.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyWordInfoDao dao = new KeyWordInfoDao(getApplicationContext());
                if (et_key_words_input.getText().toString().trim().length() == 0) {
                    Toast.makeText(AddKeyWordsInfosDailogActivity.this, "請輸入關鍵字或者取消!", 300).show();
                    return;
                }
                if (et_key_words_decribe.getText().toString().trim().length() == 0) {
                    Toast.makeText(AddKeyWordsInfosDailogActivity.this, "請輸入關鍵字描述內容或者取消!", 300).show();
                    return;
                }
                KeyWordInfo info = new KeyWordInfo();
                info.setKey_word_info(et_key_words_input.getText().toString().trim());
                info.setKey_word_decribe(et_key_words_decribe.getText().toString().trim());
                dao.addKeyWordInfos(info);
                info = null;
                setResult(ADD_KEY_INFO_SCUCESS, getIntent());
                AddKeyWordsInfosDailogActivity.this.finish();
            }
        });

        mCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                AddKeyWordsInfosDailogActivity.this.finish();
            }
        });
    }

    private void init() {
        et_key_words_input = (EditText) findViewById(R.id.et_key_words_input);
        et_key_words_decribe = (EditText) findViewById(R.id.et_key_words_decribe);
        mSure = (Button) findViewById(R.id.btn_sure);
        mCancel = (Button) findViewById(R.id.btn_cancel);
    }
}

版面檔:

<?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="match_parent"
    android:background="#ffffff"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="添加關鍵字"
        android:gravity="center" />

    <TextView
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="請輸入需要攔截的關鍵字(最多16個字,允許漢字,字母,數字)"
        android:gravity="center" />

    <EditText
        android:id="@+id/et_key_words_input"
        android:layout_marginTop="5dp"
        android:layout_width="match_parent"
        android:layout_height="55dp" />

    <EditText
        android:id="@+id/et_key_words_decribe"
        android:layout_marginTop="5dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:hint="輸入描述內容" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/btn_cancel"
            android:layout_width="160dp"
            android:layout_height="55dp"
            android:text="取消"
            android:layout_alignParentLeft="true"
            android:background="@drawable/sure_cancel_selector" />

        <Button
            android:id="@+id/btn_sure"
            android:layout_width="wrap_content"
            android:layout_height="55dp"
            android:layout_alignParentRight="true"
            android:layout_toRightOf="@+id/btn_cancel"
            android:text="確定"
            android:background="@drawable/sure_cancel_selector" />
    </RelativeLayout>
</LinearLayout>

效果圖:

該選哪一種

三者的取捨其實很清楚:AlertDialog 用最少程式碼換到系統標準外觀,適合純文字確認;Dialog 適合自訂版面但不便輸入;Activity 樣式視窗自由度最高,代價是要自己處理半透明背景(在 theme 裡設 android:windowIsTranslucent 與 windowBackground)以及回傳結果的 setResult 約定。

無論哪一種,記得對話框必須持有一個有效的 Activity Context,且要在 Activity 進入背景前妥善 dismiss,否則很容易拿到 WindowLeaked 的錯誤。若使用 Fragment,優先考慮 DialogFragment,它能跟著 Fragment 生命週期一起被管理,省去這些手動處理。

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