Android 覆蓋AlertDialog裡的按鈕事件並顯示Toast

網上找到的多數是:

控制其不消失,和消失。

1
//                  /** 假設對話框已經關閉,欺騙系統,以保持輸入窗口**/
2
                    try {
3
                        Field field = this.getClass().getSuperclass().getDeclaredField( "mShowing" );
4
                        field.setAccessible( true );
5
                        field.set(this, bSucceed);
6
                    } catch (Exception e){
7
                        e.printStackTrace();
8
                    }
 

還可以

用OnClicklistener覆蓋DialogInterface.OnClicklistener
01
//可以使用AlerDialog.Builder,並顯示一個Toast。//隻要你覆蓋按鈕的OnClickListener,就可以觸發Toast,顯示在對話框上。//並決定對話框是否消失 public void showToastOnDialog(final Context context) {
02
     AlertDialog.Builder builder = new AlertDialog.Builder(context);
03
     builder.setTitle("Dialog title");
04
     builder.setMessage("Dialog message");
05
     builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
06
      @Override
07
      public void onClick(DialogInterface dialog, int which) {
08
       // Do nothing, you will be overriding this anyway
09
      }
10
     });
11
     builder.setNegativeButton(android.R.string.cancel,
12
       new DialogInterface.OnClickListener() {
13
      @Override
14
      public void onClick(DialogInterface dialog, int which) {
15
       // You can implement code here, because you wont be
16
       // overriding this
17
      }
18
     });
19
     final AlertDialog dialog = builder.create();
20
     // Make sure you show the dialog first before overriding the
21
     // OnClickListener
22
     dialog.show();
23
     // Notice that I`m not using DialogInterface.OnClicklistener but the
24
     // View.OnClickListener
25
     dialog.getButton(Dialog.BUTTON_POSITIVE).setOnClickListener(
26
       new View.OnClickListener() {
27
 
28
        @Override
29
        public void onClick(View v) {
30
 
31
         Toast toast = Toast.makeText(context,
32
           "I`m a toast on top of a dialog.",
33
           Toast.LENGTH_LONG);
34
         toast.show();
35
         // Because you are overriding the OnClicklistener, the
36
         // dialog will not auto dismiss after clicking
37
        ////otherwise //dialog.dismiss();
38
         dialog.dismiss();
39
        }
40
       });
41
    }
 

 

測試圖片

You May Also Like