2. MainActivity.java
package org.me.android_multiitemdialog; 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 showDialogButton; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); showDialogButton = (Button) findViewById(R.id.showDialogButton); final AlertDialog mutiItemDialog = getMutiItemDialog(new String[]{"牛排","雞排","豬排"}); showDialogButton.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View view){ //顯示對話框 mutiItemDialog.show(); } }); } public AlertDialog getMutiItemDialog(final String[] items) { Builder builder = new Builder(this); //設定對話框內的項目 builder.setItems(items, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog,int which){ //當使用者點選對話框時,顯示使用者所點選的項目 Toast.makeText(MainActivity.this, "您選擇的是"+items[which], Toast.LENGTH_SHORT).show(); } }); 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/showDialogButton" android:layout_width="150px" android:layout_height="50px" android:text="多個選項的對話框"> </Button> </LinearLayout>4. 按下「多個選項的對話框」按鈕之後出現的畫面。
沒有留言:
張貼留言