アラートダイアログを表示

広告

アラートダイアログでは単にユーザーにメッセージを表示させる場合と、メッセージに対して複数のボタンを用意し押されたボタンによって異なる処理をする場合などで使われます。

ここでは単にユーザーに対してメッセージを表示し、ボタンをクリックするとダイアログが閉じるだけのダイアログを表示させてみます。「AlertDialog」クラスで用意されているstaticメソッドである「show」メソッドを使います。

Display a simple alert dialog. This convenience method constructs an 
AlertDialog and shows it.

Parameters:
  context  the context in which this alert is created.
  title  the title to be shown in the alert, pass null will not show 
    a title
  message  the alert message in the alert.
  buttonText  the text to be shown in the button, pass null will make 
    the alert buttonless.
  cancelable  if true, clicking the BACK button will dismiss the alert.

1番目の引数には引数にはダイアログを作成する元になった「Context」クラスのオブジェクトを指定します。ここでは(「Activity」クラスを継承したクラスのオブジェクトの)自分自身を表す「this」を指定して下さい。

2番目の引数にはダイアログのタイトルに表示される文字列、3番目の引数にはダイアログにメッセージとして表示される文字列、4番目の引数にはダイアログに設置されるボタンに表示される文字列を指定して下さい。

5番目の引数にはエミュレーターの「Back」キー(又はキーボードの「ESC」キー)を有効にするかどうかを設定します。「true」を設定した場合は通常と同じく「Back」キーによって一つ前の画面に戻ります。「false」を設定した場合は「Back」キーが無効となりボタンをクリックしないとダイアログは閉じません。

具体的には次のように記述します。

package jp.javadrive.android;

import android.app.Activity;
import android.os.Bundle;
import android.app.AlertDialog;

public class Test02_01 extends Activity {
    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        AlertDialog.show(this, "Alert Test", "Hello", "ok", false);
    }
}

※簡略化するために上記のように記述していますが、上記では一瞬表示されて消えてしまいます。より具体的には下記のサンプルを見てください。

サンプルプログラム

それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。

Test02_01.java

package jp.javadrive.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.app.AlertDialog;

public class Test02_01 extends Activity {
    private final int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT;

    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        setContentView(linearLayout);

        final Button button = new Button(this);
        button.setText("Open Dialog");
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                AlertDialog.show(Test02_01.this, "Alert Test", 
                  "Hello, This is Alert Dialog.", "ok", false);
            }
        });
        linearLayout.addView(button, 
          new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
    }
}

ビルド後にエミュレーター上で実行します。

アラートダイアログを表示

画面に表示されたボタンをクリックして下さい。ダイアログが表示されます。

アラートダイアログを表示

ダイアログに表示されているボタンには、デフォルトでクリックするとダイアログが閉じるように設定されているようです。ボタンをクリックするとダイアログは閉じます。

アラートダイアログを表示

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。