简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM