【Android】AlertDialogの表示(YES/NO/CANCELボタン付き)

2019年7月29日

今回は「YES/NO/CANCELボタン」付きのダイアログの表示方法です。
ボタンを押すと、下記のようなダイアログを表示します。
YES/NO/Cancelボタンダイアログ

●ソースコード
「R.layout.main」にボタンを配置し、
「android:onClick="BtnClick"」を設定し使用するソースです。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class TestDialog extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    //ボタンクリックイベント(XMLにandroid:onClickを記述)
    public void BtnClick(View v) {
        if(v.getId() == R.id.button0)
        {
            showDialog(0);
        }
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        // ダイアログが複数ある場合にidを使用する
        if (id == 0) {
            Dialog dialog = super.onCreateDialog(id);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setCancelable(false);
            builder.setIcon(android.R.drawable.ic_dialog_alert);
            builder.setTitle("YES/NO/Cancelダイアログ");
            builder.setMessage("ダイアログのテストです!");
            builder.setPositiveButton("YES",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        //YESボタンを押した時の処理があればここに記述する
                    }
                });
            builder.setNeutralButton("NO",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        //NOボタンを押した時の処理があればここに記述する
                    }
                });
            builder.setNegativeButton("CANCEL",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        //CANCELボタンを押した時の処理があればここに記述する
                    }
                });
            dialog = builder.create();
        }
    }
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);
        if (id == 0) {
            //ダイアログの内容に変更がある場合に記述
        }
    }
}

スポンサーリンク