How to get switch button status and pass to another activity using shared preferences

强颜欢笑 提交于 2019-12-11 18:33:54

问题


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


回答1:


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

Get State:

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


来源:https://stackoverflow.com/questions/32110178/how-to-get-switch-button-status-and-pass-to-another-activity-using-shared-prefer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!