Search code examples
androidmenuitemoptionmenu

one menu item for two actions


I have option menu configured and one of the items is used to enable a service in the background.

When the action takes place I am changing the item title from "Enable Service" to "Disable service" and setting a boolean value accordingly.

the issue starts when the app closes and then the class is reloaded. The boolean would be reset to the initial value.

What I would like to know is:

  1. what is the best practice to use for having one item menu that does different actions based on it's status.
  2. What is the best practice for keeping the boolean value in his last state? (shared preferences?)

Solution

  • If you want to store primitive values then the best practice is use shared preferences, then when ever user close the app then you can store the value in shared preference then next time user open the app you can simply get value from shared preferences.

    By using single menu item you can handle two actions "Enable Service" and "Disable service" based on value getting from shared preferences.