Search code examples
androidmultichoiceitems

Android setMultiChoiceItems


When I click a button a dialog pops up with multiple selection checkbox. When I select and click on ok it pops up another dialog with selected item.If i close the dialog by clicking outside the dialog and again press the button to show the dialog to select and select and click ok it appends the result from previous selection. I don't want to append the result. What am I not understanding or making mistake? code is here

@Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_tab2, container, false);
        Button button = (Button) view.findViewById(R.id.displayBox);
        final List<String> selectedItems = new ArrayList<String>();
        final String[] itemList = {"Item1", "Item2", "Item3", "Item1", "Item2", "Item3", "Item1", "Item2", "Item3", "Item1", "Item2", "Item3"};
        final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
        builder.setTitle("Multi Select");
        builder.setMultiChoiceItems(itemList, null, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                if (isChecked) {
                    selectedItems.add(itemList[which].toString());
                }
            }
        }).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ListView listView = new ListView(view.getContext());
                listView.setAdapter(new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_list_item_1, selectedItems));
                Dialog dialog1 = new Dialog(view.getContext());
                dialog1.setTitle("Selected Informations");
                dialog1.setContentView(listView);
                dialog1.show();
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.show();
            }
        });
        return view;
    }

Solution

  • Try this,

    ListView listView = new ListView(view.getContext());
                    listView.setAdapter(new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_list_item_1, selectedItems));
    

    //Clear your listview

    selectedItems.clear();
    
                Dialog dialog1 = new Dialog(view.getContext());
                dialog1.setTitle("Selected Informations");
                dialog1.setContentView(listView);
                dialog1.show();