Search code examples
androidandroid-studiocheckboxandroid-alertdialogandroid-checkbox

I have an alertDialog in which i have check boxes . I want to retain the values of the check boxes checked in by the user


I want to retain the checkbox values entered by the user. I want the selected values to be there when the alert dialog is opened again. I have the checkboxes in alert dialog. Once the user chooses his/her choice and then comes back, I want the checkboxes to be checked with the previous user input until the app closes. Is there a way to do so?


Solution

  • Please try one this

    Use two Global variable one for label and other for selction.

            String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "thursday"};
            boolean[] checkedItems = {false, false, false, false, false};
    

    then on click show dialog

       private void pickWeek() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose some days");
    
       // Add a checkbox list
    
        builder.setMultiChoiceItems(days, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i, boolean isChecked) {
    
                    checkedItems[i]=isChecked;
                // The user checked or unchecked a box
            }
        });
    
        // Add OK and Cancel buttons
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // The user clicked OK
            }
        });
        builder.setNegativeButton("Cancel", null);
    
        // Create and show the alert dialog
        AlertDialog dialog = builder.create();
        dialog.show();
    }