如何使用共享首选项获取切换按钮状态并传递到另一个活动 [英] How to get switch button status and pass to another activity using shared preferences

查看:22
本文介绍了如何使用共享首选项获取切换按钮状态并传递到另一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆