一个菜单项用于两个操作

one menu item for two actions

我配置了选项菜单,其中一项用于在后台启用服务。

当动作发生时,我将项目标题从 "Enable Service" 更改为 "Disable service" 并相应地设置一个布尔值。

当应用程序关闭然后 class 重新加载时,问题就开始了。布尔值将重置为初始值。

我想知道的是:

  1. 让一项菜单根据其状态执行不同操作的最佳做​​法是什么。
  2. 将布尔值保持在最后状态的最佳做法是什么? (共享偏好?)

如果您想存储原始值,那么最佳做法是使用 共享首选项,然后当用户关闭应用程序时,您可以将值存储在共享首选项中,然后下次使用用户打开应用程序,您可以简单地从共享偏好中获取价值。

通过使用单个菜单项,您可以根据从共享首选项获取的值处理两个操作 "Enable Service" 和 "Disable service"。

1.) 把它放在同一个地方,同时不同的icons/names 彼此有区别地相关。例如(开/关)name/icon.

2.) 使用共享首选项是可行的方法,因为您只存储原始值。它比使用 sqlite 更快。

我就是这样做的 当您加载 Activity..

SharedPreferences sharedPreferences;
static int currentAction;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_setting);
    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("MyAction", Context.MODE_PRIVATE);
    if (sharedPreferences.getInt("Action", 0) == 0) {  //  0 for Enable Service
        // set menu as Enable
        currentAction = 0;
    } else {   //  1 for Disable service
        // set menu as Disable
        currentAction = 1;
    }

}

然后当您单击菜单项时..

if (currentAction == 0) {
        //Do Action for Enable and change Action
        currentAction = 1;
    } else {
        //Do Action for Disable and change Action
        currentAction = 1;
    }
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt("Action", currentAction);
    editor.commit();
    }

希望对您有所帮助...!!