vendredi 13 décembre 2019

Kotlin - How to save state of checkboxes in custom alertdialog?

I am trying to keep the state of my checkboxes on checked if there were any checkboxes left which were selected.

I have the following dialog for it:

fun showMultipleChoiceDialog(options: Array<String>?, listener: DialogInterface.OnMultiChoiceClickListener) {
        if (options != null && options.isNotEmpty()) {
            val dialog = AlertDialog.Builder(SharedInstance.instance.context)
            .setMultiChoiceItems(options, null, listener)
            .setPositiveButton("Ok", DialogInterface.OnClickListener { dialog, which -> dialog.dismiss() })
            .create()
            dialog.show()
        }
    }

And I have the following code already:

days_picker.setOnClickListener {
            val allDays = ArrayList(days.values)
            val allStringDays = arrayOf("Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag")
            var checkedItems: MutableList<String> = mutableListOf()
            SearchProfileDialogHelper.selectedDays.clear()
            searchProfile.days.clear()

            DialogHelper.showMultipleChoiceDialog(allStringDays, DialogInterface.OnMultiChoiceClickListener { _, which, isChecked ->
                if(isChecked){
                    SearchProfileDialogHelper.selectedDays.add(allDays[which])
                    checkedItems.add(allDays[which])
                }
                if(!isChecked){
                    SearchProfileDialogHelper.selectedDays.remove(allDays[which])
                    checkedItems.remove(allDays[which])
                    if(checkedItems.size == 0) {
                        days_text.setText("Stel in voor welke dagen u beschikbaar bent.")
                    }
                }
}

Right now when I select checkboxes it works fine. If I unselect a checked checkbox it works fine as well. But what I still want to include in my project is being able to press the OK button without selecting anything and keeping the default text if there was a selection made before that. (Otherwise it already shows the default text) and most importantly I want to save the state of which checkboxes were checked until the user changes this again. So whenever I re-open my dialog I want to see what the user had checked the last time.

My problem is that I can not seem to find out how to call a checkbox and set it to a certain state. I am already saving the checkeditems in a list so that's not the issue here. The helper function showMultipleChoiceDialog is from one of my colleagues hence why I am having trouble understanding how to let the state remain the same before anyone changes anything.

So I am hoping there are people who can help me out!

I already checked the following topics on stack:

And several youtube video's already but most of them work with stuff like findViewById and are working in activity's while I am working in fragments.




Aucun commentaire:

Enregistrer un commentaire