-5

我想知道如何使用只能选择 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 个项目时如何阻止选择项目?

4

2 回答 2

1
  1. 实现一个可检查的列表视图,如此处所示 。
  2. 在适配器中保留一个Collection已检查的项目(通过实现setOnCheckedChangeListener列表项中包含的复选框,并在每次检查项目时将其添加到此集合中。
  3. 最后,使用此集合的大小来确定允许/禁止单击复选框。
于 2013-03-27T04:00:03.303 回答
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();
}
于 2013-03-27T04:50:04.017 回答