1. 利用AlertDialog物件來顯示對話框,並利用字串陣列來標示選項的標題。

2. MainActivity.java

01.package org.me.android_multiitemdialog;
02.import android.app.Activity;
03.import android.app.AlertDialog;
04.import android.app.AlertDialog.Builder;
05.import android.content.DialogInterface;
06.import android.os.Bundle;
07.import android.view.View;
08.import android.widget.Button;
09.import android.widget.Toast;
10. 
11.public class MainActivity extends Activity {
12. 
13.    private Button showDialogButton;
14.    @Override
15.    public void onCreate(Bundle icicle) {
16.        super.onCreate(icicle);
17.        setContentView(R.layout.main);
18.        showDialogButton = (Button) findViewById(R.id.showDialogButton);
19.        final AlertDialog mutiItemDialog = getMutiItemDialog(new String[]{"牛排","雞排","豬排"});
20. 
21.        showDialogButton.setOnClickListener(new Button.OnClickListener(){
22.            @Override
23.            public void onClick(View view){
24.                //顯示對話框
25.                mutiItemDialog.show();
26.            }
27.        });
28.    }
29. 
30.    public AlertDialog getMutiItemDialog(final String[] items) {
31.        Builder builder = new Builder(this);
32.        //設定對話框內的項目
33.        builder.setItems(items, new DialogInterface.OnClickListener(){
34.           @Override
35.           public void onClick(DialogInterface dialog,int which){
36.               //當使用者點選對話框時,顯示使用者所點選的項目
37.               Toast.makeText(MainActivity.this"您選擇的是"+items[which], Toast.LENGTH_SHORT).show();
38.           }
39.        });
40.        return builder.create();
41.    }
42.}


3. main.xml(Layout)

01.<?xml version="1.0" encoding="UTF-8"?>
02.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03.    android:orientation="vertical"
04.    android:layout_width="fill_parent"
05.    android:layout_height="fill_parent">"
06.    <Button
07.        android:id="@+id/showDialogButton"
08.        android:layout_width="150px"
09.        android:layout_height="50px"
10.        android:text="多個選項的對話框">
11.    </Button>
12.</LinearLayout>

 

 

4. 按下「多個選項的對話框」按鈕之後出現的畫面。


 

 


arrow
arrow
    全站熱搜

    小犬 發表在 痞客邦 留言(0) 人氣()