[英]how to save the state of switch(button) in android
I am using switch
(like android togglebutton
) instead of normal buttons in my android app. 我在我的android应用中使用了
switch
(例如android togglebutton
)而不是普通按钮。 The code works fine while enabling and disabling switches. 在启用和禁用开关的同时,代码运行良好。 But i want to store the state of the switch.
但我想存储开关的状态。 Suppose i enable the switch and close my application the background code will run fine but the switch state will change to disabled.
假设我启用了开关并关闭了我的应用程序,则后台代码可以正常运行,但是开关状态将变为禁用状态。
Every time when i close the application the switch state becomes disabled. 每当我关闭应用程序时,开关状态都会被禁用。 Is there any way to store the switch State?
有什么办法可以存储开关状态?
mySwitch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (mySwitch.isChecked()) {
SharedPreferences.Editor editor = getSharedPreferences ("com.mobileapp.smartapplocker",
MODE_PRIVATE).edit();
editor.putBoolean("Service On", true);
editor.commit();
}
else {
SharedPreferences.Editor editor = getSharedPreferences ("com.mobileapp.smartapplocker",
MODE_PRIVATE).edit();
editor.putBoolean("Service Off", false);
editor.commit();
}
}
}
I think you are confused on how shared preferences work in android. 我认为您对共享首选项在android中的工作方式感到困惑。 They are basically key value pairs.
它们基本上是键值对。 So in order to retrieve a particular value, the key has to be same.
因此,为了检索特定值,密钥必须相同。
Giving you an example below: 在下面给你一个例子:
mySwitch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
SharedPreferences.Editor editor = getSharedPreferences("com.mobileapp.smartapplocker", MODE_PRIVATE).edit();
editor.putBoolean("service_status", mySwitch.isChecked());
editor.commit();
}
}
Now where ever you are check for service 现在无论您在哪里检查服务
SharedPreferences prefs = getSharedPreferences("com.mobileapp.smartapplocker", MODE_PRIVATE);
boolean switchState = pref.getBoolean("service_status", false);
if(switchState){
//Do your work for service is selected on
} else {
//Code for service off
}
Hope that helps 希望能有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.