我有以下代码可以从用户那里获得多种选择:
protected Button selectColoursButton;
protected CharSequence[] colours = { "Red", "Green", "Blue", "Yellow", "Orange", "Purple", "MAGENTA", "WHITE", "SKYBLUE" };
protected ArrayList<CharSequence> selectedColours = new ArrayList<CharSequence>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
selectColoursButton = (Button) findViewById(R.id.select_colours);
selectColoursButton.setOnClickListener(test);
}
View.OnClickListener test = new View.OnClickListener() {
public void onClick(View v) {
switch(v.getId()) {
case R.id.select_colours:
// TODO: Show the colours dialog
showSelectColoursDialog();
break;
default:
break;
}
}
};
protected void showSelectColoursDialog() {
boolean[] checkedColours = new boolean[colours.length];
int count = colours.length;
for(int i = 0; i < count; i++)
checkedColours[i] = selectedColours.contains(colours[i]);
DialogInterface.OnMultiChoiceClickListener coloursDialogListener = new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if(isChecked) {
selectedColours.add(colours[which]);
dialog.dismiss();
}
else
selectedColours.remove(colours[which]);
onChangeSelectedColours();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Colours");
builder.setMultiChoiceItems(colours, checkedColours, coloursDialogListener);
AlertDialog dialog = builder.create();
dialog.show();
}
protected void onChangeSelectedColours() {
StringBuilder stringBuilder = new StringBuilder();
for(CharSequence colour : selectedColours)
stringBuilder.append(colour + ",");
selectColoursButton.setText(stringBuilder.toString());
}
如何将其转换为仅单选,一旦选择了选项,对话框就会关闭?