ダイアログでボタンを選択する |
ここではダイアログでボタンを選択する方法を確認していきます。
AlertDialogには「 positive 」、「 neutral 」、「 negative 」の3つのボタンが用意されています。このボタンは3つ使用してもしなくても問題ありません。 サンプルではアプリケーションの終了を確認するダイアログを表示させています。終了の確認だけなので、ボタンは2つ「positive」と「negative」を使用し、「positive(はい)」のときは「finish()」を呼び出しアプリケーションを終了し、「negative(いいえ)」のときには「cancel()」を呼び出しダイアログを消して初期画面に戻ります。 Dialog1Activity.java package goodroid.sample.dialog1; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Dialog1Activity extends Activity implements OnClickListener{ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // main.xmlからボタンオブジェクトを取得 Button btn = (Button)findViewById(R.id.button); // ボタンにリスナーを設定 btn.setOnClickListener(this); } @Override public void onClick(View v) { new AlertDialog.Builder(Dialog1Activity.this) .setMessage("アプリケーションを終了しますか?") .setCancelable(false) .setPositiveButton("はい", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Dialog1Activity.this.finish(); } }) .setNegativeButton("いいえ", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }) .show(); } } 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" > <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="ダイアログ表示" /> </LinearLayout> 実行結果 ![]() ![]() |
6006 views | コメント:0 | 2012-07-22 |
コメント
|
|
まだこの記事にコメントはありません |