DialogInterface.OnClickListener
状態:-
閲覧数:2,019
投稿日:2014-02-12
更新日:2014-02-12
AlertDialogボタンのクリックイベントに対応するリスナー
・AlertDialogのクリック処理に利用される
・クリック時に呼び出されるメソッドは「onClick」メソッド
・最初の引数には、クリックが発生したダイアログのオブジェクト、第2引数には、クリックが発生したボタンの種類が渡される
ボタンの種類
・android.content.DialogInterfaceインターフェイスで定義された、「BUTTON_NEGATIVE」、「BUTTON_NEUTRAL」、「BUTTON_POSITIVE」いずれかの定数
・AlertDialogのクリック処理に利用される
・クリック時に呼び出されるメソッドは「onClick」メソッド
・最初の引数には、クリックが発生したダイアログのオブジェクト、第2引数には、クリックが発生したボタンの種類が渡される
ボタンの種類
・android.content.DialogInterfaceインターフェイスで定義された、「BUTTON_NEGATIVE」、「BUTTON_NEUTRAL」、「BUTTON_POSITIVE」いずれかの定数
クラス構成
親クラス
子クラス
DatePickerDialog, DialogPreference, EditTextPreference, ListPreference, MultiSelectListPreference, Spinner, TimePickerDialog
コード例
例1
(ダイアログ)ボタンをクリックしたときに、トーストを表示
・ボタンのイベント処理/無名クラス利用
▼ /HelloAndroid6/src/android/style/HelloAndroid6Activity.java
package android.style;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;
public class HelloAndroid6Activity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// ダイアログの生成と表示
AlertDialog.Builder dlg =
new AlertDialog.Builder(this);
dlg.setTitle("sample"); // タイトル設定
dlg.setMessage("アラートダイアログ"); // メッセージ設定
// ボタン設定
dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(HelloAndroid6Activity.this,
"OKボタンクリック", Toast.LENGTH_LONG).show();//第1引数でHelloAndroid6Activityを指定している理由は、単にthisだけでは無名クラスのオブジェクトを指定したことになってしまうから
}
});
dlg.show(); // ダイアログの生成と表示
}
}
・xml … レイアウト
▼/HelloAndroid6/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>