How to handle ToggleButton state in OnPause and OnResume state

128 Views Asked by At

I am facing problem with toggle button state on onResume() and onPause() state.

Activity - A (first user toggle ON the button) then go back to Activity - B, then it will comeback to Activity - A then I want toggle Button is ON not OFF, how to handle this state in android.

2

There are 2 best solutions below

0
Mosius On

By default Activity handles its components state which has an id attribute.

If it's not acting like that, you can use onSaveInstanceState and onRestoreInstanceState to handle components state manually:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);

  savedInstanceState.putBoolean("Toggle1", toggle.isChecked());
  // etc.
}

And to restore the state:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);

  boolean toggle1State = savedInstanceState.getBoolean("Toggle1");
  toggle1.setCheched(toggle1State);
}
2
Manish Ahire On
 toggle_relative.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
        @Override
        public void onToggle(boolean on) {
            if (on == true){
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("toggle_relative", true); // value to store
                editor.commit();
                Toast.makeText(getContext(),"Relatives will be notified in case of accidental situation",Toast.LENGTH_LONG).show();
            }else {
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("toggle_relative", false); // value to store
                editor.commit();
            }
        }
    });







  @Override
public void onResume() {
    super.onResume();

    boolean boll_toggle_relative = preferences.getBoolean("toggle_relative", false);  //default is true
    if (boll_toggle_relative == true)
    {
        toggle_relative.setToggleOn();
    }
    else
    {
        toggle_relative.setToggleOff();
    }

}