利用AlertDialog物件來顯示對話框,並利用字串陣列來標示選項的標題。
package com.rex.multiitemdialog;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Main extends Activity {
private Button showDialogButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showDialogButton=(Button)findViewById(R.id.howDialogButton);
final AlertDialog mutiItemDialog=getMutiItemDialog(new String[]{"牛排","雞排","豬排"});
showDialogButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
//顯示對話框
mutiItemDialog.show();
}
});
}
private AlertDialog getMutiItemDialog(final String[] items) {
Builder builder=new Builder(Main.this);
//設定對話框內的項目
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//當使用者點選對話框時,顯示使用者所點選的項目
Toast.makeText(Main.this, "您選擇的是"+items[which], Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
----------------------------------------------------------------------------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main" >
<Button
android:id="@+id/howDialogButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="39dp"
android:layout_marginTop="30dp"
android:text="多個選項的對話框" />
</RelativeLayout>
---------------------------------------------------------------------------------
沒有留言:
張貼留言