Search code examples
androidtogglebutton

Preserving toggle button state on my activity


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.some_layout);
    toggleButton=(ToggleButton) findViewById(R.id.toggleButton1);
}
@Override
public void onSaveInstanceState(Bundle save) {
    super.onSaveInstanceState(save);
    save.putBoolean("ToggleButtonState", toggleButton.isChecked());
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    toggleButton.setChecked(savedInstanceState.getBoolean("ToggleButtonState",false);
}

It seem like it should work, but if i do the following:

  1. run my application by its icon on applications menu
  2. checking the toggle button
  3. going back to home screen by pressing the back button
  4. activating my application from its icon again

i get to see my toggle button unchecked, why is it so? and how do i overcome this?


Solution

  • I missed what save and restore methods are for, but to achieve the functionality i was looking for i did the following:

    public class MainActivity extends Activity {
    
        private ToggleButton toggleButton;
        private static Bundle bundle = new Bundle();
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            toggleButton = (ToggleButton)findViewById(R.id.toggleButton1);
        }
    
    
    
        @Override
        public void onPause() {
            super.onPause();
            bundle.putBoolean("ToggleButtonState", toggleButton.isChecked());
        }
    
        @Override
        public void onResume() {
            super.onResume();
            toggleButton.setChecked(bundle.getBoolean("ToggleButtonState",false));
        }
    }