0

I have built a UI with XML that contains four check boxes and a progress bar. I want to use Kotlin to make the progress in the progress bar increase by 25% for each box checked(That progress should disappear if the button is unchecked). I haven't been able to find a specific tutorial on how to do this, does anyone know how I would do this?

new_guy91
  • 17
  • 5

1 Answers1

0

Basic strategy is to create a check box listener that updates the progress bar based on current state of all the check boxes. Then add this listener to all four of your check boxes. Example that assumes use of view binding:

// in Activity.onCreate or in Fragment.onViewCreated:
val checkBoxes = with(binding) { listOf(checkBoxA, checkBoxB, checkBoxC, checkBoxD) }

val listener = OnCheckedChangeListener { _, _, ->
    val numberChecked = checkBoxes.count { it.isChecked }
    binding.progressBar.setProgress(100 * numberChecked / checkBoxes.size, true)
}

for (checkBox in checkBoxes) {
    checkBox.onCheckedChangeListener = listener
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • Hi Tenfour04, thank you for your reply! the checkBox.onCheckedChangeListener = listener part is giving me an error. are you sure about it? – new_guy91 Nov 28 '22 at 22:49
  • I think this will help you with listener: [answer](https://stackoverflow.com/a/8386876/7699617) – SerjantArbuz Nov 28 '22 at 23:06
  • @SerjantArbuz I looked at it, I don't understand how it applies to this use case. – new_guy91 Nov 28 '22 at 23:17
  • Sorry, I wrote this answer from memory. I’m away from computer so I can’t test it myself. What is the error? Did you import CompoundButton.OnCheckedChangeListener, or a different one? – Tenfour04 Nov 29 '22 at 02:12
  • Replace `checkBox.onCheckedChangeListener = listener` with this `checkBox.setOnCheckedChangeListener(listener)`. And this `OnCheckedChangeListener` to this `CompoundButton.OnCheckedChangeListener`. – SerjantArbuz Nov 29 '22 at 08:21