ユーザーから複数の選択肢を取得する次のコードがあります。
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());
}
選択が選択されると、ダイアログが閉じます。