This application shows how to create and use Menus in an Android application. Displayed on the screen is a simple layout in which text with a solid colored background appears within a differently colored border. By opening the menu the colors can be changed by selecting one of the different options.
First we will take a look through the project to see what is happening, click here to download the source.
Open the ThemeChooser.java file located in the src/ directory in edu.calpoly.android package
Take a look at the public void onCreate(Bundle savedInstanceState) method, this method is called when an Activity is first started and is used for initializing the Activity
onCreateOptionsMenu(Menu menu) is the method that is called when the Menu button and an Android device is pressed
The Menu consists of a single item for choosing the theme, this is a special item called a SubMenu which opens an additional menu window
Three MenuItems are added, one for each available theme, integer constants are used to identify each item in the SubMenu.add() method and they are all a part of the same group
Finally the group is set as checkable, which will add a check box next to each item to indicate which is currently selected
The onMenuItemClick method is called when one of the MenuItems are clicked. This method determines which item was clicked and changes the theme accordingly
See how the application works by running it on a device or emulator, it will look something like this when the menu is open:
To modify the application you will be adding the ability to save a default theme using Preferences to be used when the application opens again. Note that with the current implementation regardless of what the theme was when the application is closed, when it opens again it will always be red and orange.
First add an integer member variable to store the current theme being used. In the onMenuItemClick method add code to update this member variable with the current theme
You will now need to override the Activity's public void onPause() method to store the application's state
Make a call the super.onPause()
Call getPreferences(MODE_PRIVATE) to obtain a reference to a SharedPreferences object for this Activity
To edit the preferences you will need to use the Editor class, which you can get by calling SharedPreferences.edit()
Use Editor.putInt() to store the current theme, the first argument is a String key that is used to access this preference later, so create a final member variable to store a constant string to use for this key
Now commit the changes using the Editor.commit() method
To retrieve the stored theme when the Activity starts up again override the Activity.onResume() method
Obtain the SharedPreferences the same way as in onPause()
Use the SharedPreferences.getInt() method to determine which theme to use, the first argument is the same String key you used before and the second argument is a default value to use if no preference exists for that key