调用AlertDialogBuilder的setSingleChoiceItems方法就可以创建一个单选列表的对话框。
以下为布局文件main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ffffff">
<Button
android:layout_width="300dp"
android:layout_height="80dp"
android:text="CLICK ME"
android:textSize="60dp"
android:gravity="center"
android:id="@+id/button"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:background="#553388"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="180dp"
android:layout_marginTop="350dp"
android:text="New Text"
android:textSize="40dp"
android:gravity="center"
android:id="@+id/textView"
android:layout_gravity="center_horizontal" />
</LinearLayout>
java程序如下:
package com.example.administrator.singlechoicedialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DialogTitle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class SingleChoiceDialog extends AppCompatActivity {
final int SINGLE_DIALOG = 0x113;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bn = (Button) findViewById(R.id.button);
//Bind an event listener for the button
bn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Display the dialog
showDialog(SINGLE_DIALOG);
}
});
}
//Rewrite the method onCreateDialog to create the dialog
public Dialog onCreateDialog(int id, Bundle state){
//Judge which dialog should be created
switch(id){
case SINGLE_DIALOG:
AlertDialog.Builder b = new AlertDialog.Builder(this);
//Set the dialog's icon
b.setIcon(R.drawable.icon);
//Set the dialog's title
b.setTitle("Single Choice Dialog");
//Set up multiple lists for dialog
b.setSingleChoiceItems(new String[]
{"RED", "GREEN", "BLUE"}
//The second item is selected by default
, 1
//Set the listener
, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
TextView textView = (TextView)findViewById(R.id.textView);
//'i' represent the list which is clicked
switch(i){
case 0:
textView.setBackgroundColor(Color.RED);
break;
case 1:
textView.setBackgroundColor(Color.GREEN);
break;
case 2:
textView.setBackgroundColor(Color.BLUE);
break;
}
}
}
);
//Add a OK button, this button is used to close the dialog
b.setPositiveButton("OK", null);
//create the dialog
return b.create();
}
return null;
}
}
运行结果如下: