DialogInterface.OnClickListenerインターフェース
「DialogInterface.OnClickListener」インターフェースはダイアログに含まれるボタンのクリック処理に使用されます。
android.content public static interface android.content.DialogInterface.OnClickListener
クリック時に呼び出されるメソッドは「onClick」メソッドとなります。
onClick public void onClick(DialogInterface dialog, int whichButton)
This method will be invoked when a button in the dialog is clicked. Parameters: dialog The dialog that was cancelled will be passed into the method. whichButton The button that was clicked, i.e. BUTTON1 or BUTTON2.
1番目の引数にはクリックが発生した「android.content.DialogInterface」インターフェースをを実装したクラスのオブジェクトが渡されてきます。インターフェースを実装したクラスとしては「AlertDialog」クラス, 「DatePickerDialog」クラス, 「Dialog」クラス, 「ProgressDialog」クラス, 「TimePickerDialog」があります。イベント発生元のダイアログを判別するのに使用します。
2番目引数にはクリックが発生したボタンの種類が渡されてきます。ボタンの種類は「android.content.DialogInterface」インターフェースで定義されており次のどちらかです。
android.content.DialogInterface.BUTTON1 android.content.DialogInterface.BUTTON2
実装方法
実際に利用するには「android.content.DialogInterface.OnClickListener」インターフェースをインプリメントして、クラス内で「onClick」メソッドを定義します。下記は「AlertDialog」クラスを使った場合です。
import android.app.AlertDialog; import android.content.DialogInterface; public class Test extends Activity implements DialogInterface.OnClickListener{ @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); AlertDialog.show(Test.this, "Alert Test", "Hello, This is Alert Dialog.", "ok", Test.this, false, null); } public void onClick(DialogInterface dialog, int whichButton) { if (whichButton == DialogInterface.BUTTON1){ // ボタン1のクリック時の処理 }else if (whichButton == DialogInterface.BUTTON2){ // ボタン2のクリック時の処理 } } }
( Written by Tatsuo Ikura )

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