0

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?

ConcurrentHashMap
  • 4,998
  • 7
  • 44
  • 53
ammukuttylive
  • 365
  • 2
  • 6
  • 15

2 Answers2

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

Community
  • 1
  • 1
Renjith
  • 5,783
  • 9
  • 31
  • 42
1

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();
        }
    });
ConcurrentHashMap
  • 4,998
  • 7
  • 44
  • 53