1

this is my code:

tglSwitch.setOnCheckedChangeListener(new  OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             int  t= isChecked ? 1 : 0;                  
             Log.i("t",t);
    }
}

when the user check or uncheck the togglebutton , the above code will run, and when i use this code too.

tglSwitch.setChecked(true);

how can i detect OnCheckedChangeListener() only when user do it?

Manian Rezaee
  • 1,012
  • 12
  • 26
  • You can take a look to the 2nd answer, but it's not very nice : http://stackoverflow.com/questions/7187287/how-to-know-whether-user-has-changed-the-state-of-toggle-button – Bubu Mar 06 '15 at 15:41
  • @Bubu thanks but it's not corrent answer. – Manian Rezaee Mar 06 '15 at 16:01

1 Answers1

0

You should keep track of it with a separate variable

int userChecked = 0;
int checked = 0;
tglSwitch.setOnCheckedChangeListener(new  OnCheckedChangeListener() {

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
         int  userChecked= isChecked ? 1 : 0;
         int checked= isChecked? 1:0;    
         Log.i("t",userchecked);
    }
}


if(userChecked == 0){
       tglSwitch.setChecked(true);
       checked = 1;} 
else {
      userChecked = 0;
      tglSwitch.setChecked(true);
      checked = 1;
}

That way you can determine who actually checked the variable (system or not). You could also set the variable to one variable and use it -1 for system changed or 1 for user changed.

Andrew Crider
  • 45
  • 1
  • 7