-1

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.

DawidJ
  • 1,245
  • 12
  • 19
Manish Ahire
  • 550
  • 4
  • 19

2 Answers2

1

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);
}
Mosius
  • 1,602
  • 23
  • 32
0
 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();
    }

}
Manish Ahire
  • 550
  • 4
  • 19
  • `SharedPreferences` is not appropriate in this case, it will cause unexpected behavior if you lunch more than one instance of your `Activity` – Mosius Jan 06 '19 at 12:41
  • But it working fine for now, if it create any issue then ill change the code, @Mosius – Manish Ahire Jan 07 '19 at 10:36