Java (Android): ダイアログの表示

device-2013-01-03-001651

java: AlertDialogActivity.java

package jp.feb19.snippets;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class AlertDialogActivity extends Activity {

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);

		// Button を設置
		final Button button = new Button(this);
		button.setText("アラート");
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showAlert();
			}
		});
		layout.addView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

		setContentView(layout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}

	protected void showAlert() {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
		alertDialog.setTitle("Alert Dialog Test");
		alertDialog.setMessage("Hello, World.");
		alertDialog.setPositiveButton("OK", 
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// OK
			}
		});
		alertDialog.setNegativeButton("Cancel", 
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// Cancel
			}
		});
		alertDialog.setNeutralButton("Other", 
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// その他の処理
			}
		});
		alertDialog.show();
	}
}