AlertDialogで警告画面を表示する(1)
Activityで警告表示を出したい時に利用するのがAlertDialogです。
基本的な使い方を解説します。
AlertDialog.Builderを使うことで簡単にダイアログを作成できます。
ダイアログ画面で利用頻度の高いメソッドは以下の3つです。
1 2 3 | public AlertDialog.Builder setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener)public AlertDialog.Builder setNeutralButton(CharSequence text, DialogInterface.OnClickListener listener)public AlertDialog.Builder setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener) |
以下、ソースコードと解説です
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); AlertDialog.Builder alertDialog=new AlertDialog.Builder(this); // ダイアログの設定 alertDialog.setTitle("title"); //タイトル alertDialog.setMessage("massage"); //内容 alertDialog.setIcon(R.drawable.icon); //アイコン設定 alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO 自動生成されたメソッド・スタブ Log.d("AlertDialog", "Positive which :" + which); } }); // ダイアログの作成と表示 alertDialog.create(); alertDialog.show();} |
アラートダイアログの表示にはalertDialogインスタンスを生成します。
8~10行目にかけて基本的なタイトル・内容・アイコンを設定します。(アイコンは無くても問題ありません)
12行目は、PositiveButtonの設定です。
第1引数:表示文字列
第2引数:ボタンが押下されたときに呼び出されるリスナーを登録します。
利用可能なボタンは以下の3種類です。それぞれ意味としては肯定・中立・否定ですが
主に開発で使うのはOK/NGなど二択が多いでしょう。
1 2 3 | public AlertDialog.Builder setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener)public AlertDialog.Builder setNeutralButton(CharSequence text, DialogInterface.OnClickListener listener)public AlertDialog.Builder setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener) |
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 | AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);// ダイアログの設定alertDialog.setTitle("title"); //タイトルalertDialog.setMessage("massage"); //内容alertDialog.setIcon(R.drawable.icon); //アイコン設定// OKボタンの設定alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO 自動生成されたメソッド・スタブ Log.d("AlertDialog", "Positive which :" + which); }});// SKIPボタンの設定alertDialog.setNeutralButton("SKIP", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO 自動生成されたメソッド・スタブ Log.d("AlertDialog", "Neutral which :" + which); }});// NGボタンの設定alertDialog.setNegativeButton("NG", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO 自動生成されたメソッド・スタブ Log.d("AlertDialog", "Negative which :" + which); }});// ダイアログの作成と表示alertDialog.create();alertDialog.show(); |
3 Comments


