2015-10-03 31 views
0

我正在使用AlertDialog和多項選擇來顯示可檢查項目列表。如何記住多選擇提示對話框中的選定值?

當用戶選擇一些值時,我可以得到他們的索引並保存到列表中。這工作正常。

但我希望當用戶再次打開AlertDialog有他選擇之前選定/檢查值。

下面是代碼:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
    builder.setMultiChoiceItems(R.array.array_cousine, null, 
      new DialogInterface.OnMultiChoiceClickListener() { 

       @Override 
       public void onClick(DialogInterface dialog, int indexSelected, 
            boolean isChecked) { 
        if (isChecked) { 
         seletedItems.add(++indexSelected); 
        } else if (seletedItems.contains(indexSelected)) { 
         seletedItems.remove(Integer.valueOf(++indexSelected)); 
        } 
       } 
      }) 
      // Set the action buttons 
      .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int id) { 
        String[] expList = getResources().getStringArray(R.array.array_cousine); 

        for (int i = 0; i < seletedItems.size(); i++) { 
         int selected = seletedItems.get(i); 
         String selectedString = expList[selected - 1]; 
         selectedItemsName.add(selectedString); 
        } 

        StringBuilder stringBuilder = new StringBuilder(); 

        for (int j = 0; j < selectedItemsName.size(); j++) { 
         String text = selectedItemsName.get(j); 
         stringBuilder = stringBuilder.append(" "+text); 

        } 

        Log.d("TAG", "String builder: " + stringBuilder); 
        tvCusine.setText(stringBuilder); 

        dialog.dismiss(); 

       } 
      }) 
      .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int id) { 
        dialog.dismiss(); 
       } 
      }); 

    Dialog dialog = builder.create();//AlertDialog dialog; 
    dialog.show(); 

這裏是圖片:

enter image description here

回答

3

第二個參數builder.setMultiChoiceItemsboolean[]您當前傳遞爲空。要在打開時將項目顯示爲已選中,請在此陣列中以true作爲您想要檢查的每個項目的位置。這些值可以在數組創建後使用boolean[position] = value

+0

是的,我知道第二個參數接受布爾值,我傳遞null,因爲我不知道如何動態地將值添加到布爾[]。 – Zookey

+0

您不能動態更改大小。您可以通過調用boolean [position] = value來隨時更改值。你也可以有一個布爾列表的佈列表,然後在創建實例化警報對話框時調用arraylist.toArray - 馬庫斯胡珀13秒前編輯 –

+0

我已經嘗試了第二種解決方案,它不起作用。我現在會嘗試第一個解決方案。 – Zookey

1

如果您查看setMultiChoiceItems的文檔,則第二個參數是布爾數組,您可以在其中設置檢查哪些項目,哪些不是。您傳遞null,因此,不會檢查任何內容。

+0

我知道,但可以動態更改boolean []的值嗎? – Zookey