ark
ark

Reputation: 1

Save state of toggle button

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?

Upvotes: 0

Views: 1664

Answers (2)

Andrea Ebano
Andrea Ebano

Reputation: 573

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.

Upvotes: 3

Hari N Jha
Hari N Jha

Reputation: 484

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.

Upvotes: 0

Related Questions