我想知道如何使用元素列表实现对话框,我只能选择4个复选框。我怎样才能做到这一点?任何教程? 我有类似的东西:
protected void showSelectMeasurementsDialog() {
boolean[] checkedMeasurements = new boolean[measurements.length];
int count = measurements.length;
for(int i = 0; i < count; i++)
checkedMeasurements[i] = selectedMeasurements.contains(measurements[i]);
DialogInterface.OnMultiChoiceClickListener measurementsDialogListener = new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecselectedMeasurementsChecked){
if(isChecselectedMeasurementsChecked)
selectedMeasurements.add(measurements[which]);
else{
selectedMeasurements.remove(measurements[which]);
}
onChangeSelectedMeasurements();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Measurements");
builder.setMultiChoiceItems(measurements, checkedMeasurements, measurementsDialogListener);
AlertDialog dialog = builder.create();
dialog.show();
}
但我不知道当我选择了4个时如何阻止选择项目?
答案 0 :(得分:1)
Collection
已检查过的项目
适配器(通过实现setOnCheckedChangeListener
列表项中包含的复选框,并将其添加到此列表中
每次检查项目时收集。 答案 1 :(得分:1)
像这样试试。
public void dialog(View v){
String str[] = {"yyyy","xxxx","ccccc","cxcxxc","dadfssaas"};
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog, null);
ListView lv = (ListView)view.findViewById(R.id.listView1);
ArrayAdapter<String> adp = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_multiple_choice,str);
lv.setAdapter(adp);
final boolean[] checkedItems = new boolean[str.length];
alertDialog.setMultiChoiceItems(str, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// TODO Auto-generated method stub
int count = 0;
for (int i = 0; i < checkedItems.length; i++) {
// loop through the checkedItems array, if checkedItems
// increment count*/
if (checkedItems[i]) {
count++;
}
if (count == 5) {
// if the number of checked items become
// four, set the last checkedItems item 'which'
// to false and uncheck the checkbox
checkedItems[which] = false;
((AlertDialog) dialog).getListView().setItemChecked(which, false);
break;
}
}
}
});
alertDialog.show();
}