Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the state of a switch without triggering OnCheckChanged listener

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 stop
switch.setChecked(true); triggering OnCheckedChangedlistener()

like image 371
Safa Avatar asked Jan 16 '18 13:01

Safa


3 Answers

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
}
like image 187
Franco Avatar answered Oct 22 '22 06:10

Franco


You can remove that listener first and set it again after.

switch.setOnCheckChangedListener(null);
switch.setChecked(true);
switch.setOnCheckChangedListener(mOnCheckChangedListener);
like image 5
egoldx Avatar answered Oct 22 '22 06:10

egoldx


2 ways:

  1. Whenever you change programmatically, maintain a boolean variable and set it to true. In OnCheckedChangeListener(), check if has come from the user or programmatically.

  2. (Not recommended) Before you change programmatically, set yourSwtich.setOnCheckedChangeListener(null) to null. Then in next line again set your listener

like image 2
Geethakrishna Juluri Avatar answered Oct 22 '22 06:10

Geethakrishna Juluri