0

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.

1
  • 2
    I recommend using onclick listener instead. Checked change listener is a mess as it doesn't differentiate between user interaction and in-code change. Commented May 10, 2024 at 14:49

1 Answer 1

0

It's very simple, In checkedChnageListener you get buttonview "{ _, isChecked -> " here the one you _ assigned, It gives ispressed variable which only gives true if user has touched switch otherwise it will always give false

Here, it is how you use:

 switchAll.setOnCheckedChangeListener { btnView, isChecked ->
              if (btnView.isPressed) {
                if (isChecked) {
                    binding.recyclervw.post { adapter.onAllChecked(isChecked) }
                }
            }
         }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.