将arrayList传递给对话框中的setMultiChoiceItems

时间:2017-11-03 05:42:10

标签: java android arraylist android-dialog

我正在实施一个带有已检查listview的简单对话框。这就是我到目前为止所做的:

CharSequence[] items = {"Brand A", "Brand B", "Brand C"};
    AlertDialog.Builder builder = new AlertDialog.Builder(StrengthOfDemandsView.this);
    builder.setTitle("Select Brands");
    final ArrayList seletedItems=new ArrayList();

    builder.setMultiChoiceItems(items, null,
            new DialogInterface.OnMultiChoiceClickListener() {
                // indexSelected contains the index of item (of which checkbox checked)
                @Override
                public void onClick(DialogInterface dialog, int indexSelected,
                                    boolean isChecked) {
                    if (isChecked) {

                        seletedItems.add(indexSelected);
                    } else{
                        seletedItems.remove(Integer.valueOf(indexSelected));
                    }
                }
            })

         .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {

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

                }
            });

    dialog = builder.create();
    dialog.show();

问题:

最初,我将一个数组传递给setMultiChoiceItems方法并且它工作正常,但如何传递ArrayList而不是数组?像这样:

ArrayList<Products> brandList = new ArrayList<>();

每当我尝试将ArrayList传递给setMultiChoiceItems方法时,它都会给我这个错误:

Cannot resolve method 'setMultiChoiceItems(java.util.ArrayList<com.application.marketvisit.dataItem.Products>, null, anonymous android.content.DialogInterface.OnMultiChoiceClickListener)'

2 个答案:

答案 0 :(得分:2)

您需要将String数组传递给AlertDialog.Builder#setMultiChoiceItems,然后将其作为字符串数组收集

String arr = new String[brandList.size()];
for(int i=0 ; i< brandList.size();i++){
    arr[i] = brandList.get(i).getProductName();
   //getProductName or any suitable method
}

答案 1 :(得分:0)

试试这个......让我知道它是否有效..

 ArrayList<String> strBrandList = new ArrayList<String>();
   for (int i = 0; i < brandList.size(); i++) {
           strBrandList.add(brandList.get(i).getProductName())
   }