I am using a toggle button in my applications settings page. The problem is, that once I turn the toggle button on and exit from the settings page and then again go to settings, it shows that toggle button is in off state. I want it in the on state until the user turns it off, even if the app is closed... Is it possible?
-
Use shared prefrence and pass statte of it to the shared prefrenceUsman Kurd– Usman Kurd2013年02月04日 09:01:42 +00:00Commented Feb 4, 2013 at 9:01
2 Answers 2
Thats because you are not saving the state of ToggleButton. Use SharedPreference to save the state of ToggleButton on Button click.
Check this answer. This will help you
Comments
You should use SharedPreferences for that with an onCheckedChangedListener.
Here's an example how I'm handling it for a CheckBox (should be equal to a ToggleButton, so it's untested, but should work!):
ToggleButton mToggleButton = (ToggleButton) findViewById(R.id.mToggleButton);
mToggleButton.setChecked(getSharedPreferences(mSharedPreferences, MODE_PRIVATE).getBoolean("dontShowAgain", false));
mToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences settings = getSharedPreferences(mSharedPreferences, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("dontShowAgain", isChecked);
editor.commit();
}
});