2. MainActivity.java
package org.me.android_dialog; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { private Button dialogButton; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); dialogButton = (Button) findViewById(R.id.dialogButton); final AlertDialog alertDialog = getAlertDialog("這是一個對話框","請選擇......"); dialogButton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(final View view) { //顯示對話框 alertDialog.show(); } }); } private AlertDialog getAlertDialog(String title,String message){ //產生一個Builder物件 Builder builder = new AlertDialog.Builder(MainActivity.this); //設定Dialog的標題 builder.setTitle(title); //設定Dialog的內容 builder.setMessage(message); //設定Positive按鈕資料 builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //按下按鈕時顯示快顯 Toast.makeText(MainActivity.this, "您按下OK按鈕", Toast.LENGTH_SHORT).show(); } }); //設定Negative按鈕資料 builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //按下按鈕時顯示快顯 Toast.makeText(MainActivity.this, "您按下Cancel按鈕", Toast.LENGTH_SHORT).show(); } }); //利用Builder物件建立AlertDialog return builder.create(); } }
3. main.xml(Layout)
<?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">" <Button android:id="@+id/dialogButton" android:layout_width="95px" android:layout_height="40px" android:text="ShowDialog" > </Button> </LinearLayout>
4. 按下ShowDialog按鈕之後出現的畫面
沒有留言:
張貼留言