Androidアプリ開発の教科書 [ch5 ダイアログ]

目次

はじめに

先日の続きで、ちょうどダイアログを実装する用事ができたので少し踏み込んで学習。

自分の備忘録

ダイアログ

ダイアログの構成

  • タイトル
  • コンテンツエリア
  • アクションボタン
    • Neutral Button(左端)
    • Negative Button(中心)
    • Positive Button(右端)

実装の流れ

  • ビルダーを生成
  • 表示を設定
  • アクションボタンの設定
  • ダイアログオブジェクトを生成

実装

strings.xmlで指定している

orderDialog.setPositiveButton(R.string.orderDialog_btn_ok,new DialogButtonClickListener());
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    //ダイアログビルダを生成(セットしていく)
    AlertDialog.Builder orderDialog = new AlertDialog.Builder(getActivity());
    orderDialog.setTitle(R.string.orderDialog_title);
    orderDialog.setMessage(R.string.orderDialog_msg);
    orderDialog.setPositiveButton(R.string.orderDialog_btn_ok,new DialogButtonClickListener());
    orderDialog.setNegativeButton(R.string.orderDialog_btn_ng,new DialogButtonClickListener());

    //ダイアログビルダの情報をもとにダイアログを作成 
    AlertDialog dialog = orderDialog.create();
    return dialog;
}

//クリックされた時のイベント処理を記述
private class DialogButtonClickListener implements DialogInterface.OnClickListener{

    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        String msg = "";
        switch(i){
            case DialogInterface.BUTTON_POSITIVE:
                msg = getString(R.string.orderDialog_push_btn_ok);
                break;
        :

詳細

 public void onClick(DialogInterface dialogInterface, int i) 
  • DialogInterface dialogInterface(タップしたダイアログ)
  • int i (ダイアログの押下したボタンのDialogInterfaceクラス内に定義されている)
    • int BUTTON_NEGATIVE = -2;
    • int BUTTON_NEUTRAL = -3;
    • int BUTTON_POSITIVE = -1;