[Android] AlertDialog-無法被Back與Search Button cancel的Dialog

AlertDialog有時候會在需要User Input時出現,Dialog會出現幾個選項讓使用者選擇好讓系統根據選項去執行接下來的動作,當有這樣的功能需求出現時,如何確保AletDialog不被使用者以其它方式取消掉進而造成系統無法正常運作的狀況是個重要的議題,最常見的就是「Back」以及「Search」這兩個按鈕造成AlertDialog直接被取消,本文將針對如何預防此種情況發生進行說明。

範例情境:

User進入系統後,需要獲得使用者性別,作為系統外觀風格判斷的依據。


程式碼說明:

一、防止Back鍵關閉AlertDialog
AlertDialog本身就提供防止BACK Key關閉Dialog的Method,只要在建立Dialog物件時呼叫下列函式就可避免此問題發生。
alert.setCancelable(false);

二、防止Search鍵關閉AlertDialog
要避免Search鍵關閉AlertDialog,只要在alert物件上註冊setOnKeyListener,監聽User的Key Input,只要是按下Search鈕(使用KeyCode判斷)就回傳true,表示該事件已經被此Dialog所處理,否則回傳false。
//註冊key event listener
alert.setOnKeyListener(new OnKeyListener()
{
@Override
public boolean onKey(DialogInterface dialog, int code, KeyEvent event){
  if(code==KeyEvent.KEYCODE_SEARCH) //如果按下Search鈕
    return true;
  else
    return false;
  }                  
});
三、執行程式就會發現不論怎麼按「Back」、「Search」,AlertDialog都不會被取消,也就達成解決使用者造成系統流程例外的問題了。

完整程式碼:
package com.CantBeDismissDialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.view.KeyEvent;

public class CantBeDismissDialog extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //AlertDialog builder物件
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        
        //設定AlertDialog內容
        builder.setTitle("系統提示")
            .setMessage("請問你是男生還是女生?")
            .setPositiveButton("Boy", null)
            .setNegativeButton("Girl", null)
            .setCancelable(false);  //設定back鍵無法dismiss dialog
        
        //建立AlertDialog
        AlertDialog alert = builder.create();
        //顯示AlertDialog
        alert.show();
        
        //註冊key event listener
        alert.setOnKeyListener(new OnKeyListener()
        {
      @Override
      public boolean onKey(DialogInterface dialog, int code, KeyEvent event) {
       if(code==KeyEvent.KEYCODE_SEARCH) //如果按下Search鈕
        return true;
       else
        return false;
      }                  
        });
    }
}

留言

這個網誌中的熱門文章

[Android] layout_weight的妙用-讓View的大小以百分比率顯示(proportionate size)

[Android] 內部儲存體(Internal Storage)的檔案系統讀寫(File I/O)

【海外婚紗】造型篇-我的超人新祕Sunny-Yang