I have a series of toggles in a recycler view(with individual terms and conditions) and one main toggle(to acknowlege all the terms and conditions).
If the main toggle is on or off, the rest of the toggle should be the same. If any of the individual toggle is off the main toggle should be off.
This code is to acknowledge all the terms and conditions:
switchAll.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
binding.recyclervw.post { adapter.onAllChecked(isChecked) }
}
}
fun onAckAllChecked(isChecked:Boolean) {
list.forEach {
it.isChecked = isChecked
}
notifyDataSetChanged()
}
Below is the adapter code :
fun bindView(position: Int) {
val model = list[position]
itemBinding.switch.setOnCheckedChangeListener { _, isChecked ->
model.isChecked = isChecked
onSwitchClick(isChecked)
}
}
onSwitchClick higher order function in the fragment:
private val onSwitchClick: (Boolean) -> Unit = { _ ->
binding.switchAll.isChecked = viewModel.isAllSwitchOn()
}
fun isAllSwitchOn() = list.all { it.isChecked }
This works fine but when I toggle off one individual switch along with main all other switches are toggled off since the oncheckedchange listerner gets called for the main toggle.
How to fix this.