Is there any workaround helps me to programmatically change the state
of Switch widget using switch.setChecked(true);
without triggering OnCheckedChangedlistener()
?
switch.setChecked(true);
trigger OnCheckedChangedlistener()
automatically but I need it triggered only when the user changes the state manually. So I need to stopswitch.setChecked(true);
triggering OnCheckedChangedlistener()
I worked around this problem by using setOnClickListener()
instead of setOnCheckedChangeListener()
, then I can use isChecked
inside the click listener to know whether the Switch
is checked or not, e.g.:
switchView.setOnClickListener {
val isChecked = switchView.isChecked
// Do something with the check status
}
You can remove that listener first and set it again after.
switch.setOnCheckChangedListener(null);
switch.setChecked(true);
switch.setOnCheckChangedListener(mOnCheckChangedListener);
2 ways:
Whenever you change programmatically, maintain a boolean variable and set it to true. In OnCheckedChangeListener(), check if has come from the user or programmatically.
(Not recommended) Before you change programmatically, set yourSwtich.setOnCheckedChangeListener(null) to null. Then in next line again set your listener
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With