How to know whether user has changed the state of toggle button?

nila picture nila · Aug 25, 2011 · Viewed 21.7k times · Source

I have ten toggle buttons. I want to save the state of five of those buttons when clicking the home button. But I want to save it only if the user has made a change to any of the buttons' state. Is there any way to know the change in states without using setOnClickListener()?

Answer

sydd picture sydd · Jan 3, 2013

I have done the following, its not so nice, but it works:

ttsButton = (ToggleButton) findViewById(R.id.solution_ttsbutton);
ttsButton.setOnCheckedChangeListener(toggleButtonChangeListener);
...
// gets called, if the button state changes
final CompoundButton.OnCheckedChangeListener toggleButtonChangeListener = new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // The user changed the button, do something
    }
};

and I do the following, if I want to change the button programatically without executing the change listener:

ttsButton.setOnCheckedChangeListener(null);
ttsButton.setChecked(false);
ttsButton.setOnCheckedChangeListener(toggleButtonChangeListener);