繁体   English   中英

切换按钮的保存状态

[英]Save state of toggle button

默认情况下,我在活动中将切换按钮设置为true。 然后,当我移到同一活动中的其他片段时,切换按钮的状态不会改变,但是当我移至另一个活动并返回到主活动时,切换状态将被设置回默认值。

就像默认状态是true。 我在活动A中将其更改为false。我转到活动B,然后返回到活动A,然后切换按钮将再次变为true。 我希望它成为用户设置的状态。 有什么办法吗?

使用SharedPreferences ,它只是一个具有键值逻辑的文件,可以在上面保存一些简单的数据。 SharedPreferences主要用于标记(视情况而定)或存储简单的其他设置/信息:

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);
}

希望能帮助到你。

您可以实现在后台活动中的片段重新加载时保存实例状态的逻辑。 然后,您可以执行以下操作:

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;
}

使用它,它将检查是否已创建该片段的早期视图。 如果是这样,它将重用使用infalter创建新视图的视图。 希望它能解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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