如何使用共享首选项获取切换按钮状态并传递到另一个活动

编程入门 行业动态 更新时间:2024-10-24 20:24:19
本文介绍了如何使用共享首选项获取切换按钮状态并传递到另一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我在一个活动中有开关按钮,在另一个活动中有另一个开关按钮.在我的应用程序中,我想获取开关按钮天气的状态,它是打开还是关闭状态,我想将开关按钮的状态传递给另一个活动使用共享首选项,并根据第一个开关按钮状态设置出现在第二个活动中的开关按钮状态.任何人都可以告诉我如何做到这一点.提前非常感谢

I am having switch button in one activity and another switch button in another activity.In my application i want to get the status of switch button weather it was on on or off state,I want to pass the status of switch button to the another activity using shared preferences and set the switch button state which was present in the second activity according to the first switch button state. can any one tell me how to do this please.Big thanks in advance

推荐答案

添加 singleton class 并创建用于设置和获取切换按钮状态的方法.稍后您可以从任何地方访问切换按钮的状态.您还可以使用共享偏好 为此.设置状态:

Add a singleton class and create methods for setting and getting state of your toggle button. Later you can access the state of the toggle button from anywhere. You can also use shared preference for this. Set State:

SharedPreferences.Editor editor = getSharedPreferences(
            "com.ali.myapp", Context.MODE_PRIVATE).edit();
editor.putBoolean("state", yourButton1.isChecked());
editor.apply();

获取状态:

SharedPreferences prefs = getSharedPreferences(
            "com.ali.myapp", Context.MODE_PRIVATE); 
boolean state= prefs.getBoolean("state", false);
yourButton2.setChecked(state);

这篇关于如何使用共享首选项获取切换按钮状态并传递到另一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 04:52:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390127.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   按钮   首选   状态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!