0

By default I have set the toggle button true in an activity. Then when I move to other fragments within the same activity, the state of the toggle button doesn't change but when I move to another activity and return to the main activity, the toggle state will be set back to default.

Like the default state is true. I changed it to false in Activity A. I went to Activity B and returned to Activity A then now the toggle button will be true again. I want it to be the state the user have put. Any solutions?

Draken
  • 3,134
  • 13
  • 34
  • 54
ark
  • 1
  • 2
  • Do you need to change it only for current session or you want to keep that state even after app restart? – Ikazuchi Jun 28 '19 at 10:10
  • Some options would be [extending the Application class](https://stackoverflow.com/questions/456211/activity-restart-on-rotation-android/456918#456918) which works only as long as the app is alive and [SharedPreferences](https://developer.android.com/training/data-storage/shared-preferences) for permanent storage. – Markus Kauppinen Jun 28 '19 at 10:15
  • If it is only for this cycle, you can use `savedInstanceState`, check https://developer.android.com/guide/components/activities/activity-lifecycle and go to `onCreate()` topic. – Ikazuchi Jun 28 '19 at 10:17
  • @ikazuchi,keep the same state even when the app is restarted – ark Jun 28 '19 at 11:02

2 Answers2

3

Use SharedPreferences, it is just a file with KEY-VALUE logic that saves some simple data on it. SharedPreferences is mostly used for flags(as your case) or to store simple other settings/informations:

private static void saveToggle(Context context, boolean isToggled) {
    final SharedPreferences sharedPreferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("toggle_value", isToggled).apply();
}

private static Boolean loadToggle(Context context){
    final SharedPreferences sharedPreferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
    return sharedPreferences.getBoolean("toggle_value", true);
}

Hope it helps.

Andrea Ebano
  • 563
  • 1
  • 4
  • 16
0

You can implement the logic of saving the instance state when the fragment in your background activity is reloaded. The issue with the view then you can do something like:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    //Inflate the layout for this fragment or reuse the existing one
    View view = getView() != null ? getView() : 
    inflater.inflate(R.layout.fragment_fragment2, container, false);

    return view;
}

Using this, it will check whether the earlier view for the fragment has been created or not. If so then it will reuse that view intead of creating new view using infalter. Hope it will solve your issue.

Hari N Jha
  • 484
  • 1
  • 3
  • 11