如何在android中保存开关(按钮)的状态 [英] how to save the state of switch(button) in android

查看:32
本文介绍了如何在android中保存开关(按钮)的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 android 应用程序中使用 switch(如 android togglebutton )而不是普通按钮.该代码在启用和禁用开关时工作正常.但我想存储开关的状态.假设我启用开关并关闭我的应用程序,后台代码将运行良好,但开关状态将更改为禁用.

I am using switch (like android togglebutton ) instead of normal buttons in my android app. 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();
    }
  }
}

推荐答案

我认为您对共享首选项在 android 中的工作方式感到困惑.它们基本上是键值对.因此,为了检索特定值,键必须相同.

I think you are confused on how shared preferences work in android. They are basically key value pairs. So in order to retrieve a particular value, the key has to be same.

下面给你一个例子:

    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
  }

希望对你有帮助

这篇关于如何在android中保存开关(按钮)的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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