I’m wondering how to use enums in Java. I’m working on a recipe application for Android. I have a screen with four tabs in a TabHost and would like to refer to them through named constants, and I believe that it’s best to do it through an enum.
private enum mTab {
TAB_NAME(0), TAB_INGREDIENT(1), TAB_STEP(2), TAB_MEDIA(3);
final int numTab;
private mTab(int num){
this.numTab = num;
}
public int getValue(){
return this.numTab;
}
};
Now I’d like to create a different menu for each tab. For example, for TAB_INGREDIENT I’d like a menu option called “Add ingredient”, while for TAB_MEDIA I’d like a menu option called “Add image”.
I’m creating the menus through an onPrepareOptionsMenu(), like so
public boolean onPrepareOptionsMenu(Menu menu) {
// Clear menu before showing new menu
menu.clear();
super.onPrepareOptionsMenu(menu);
// Create new menu based on current tab
MenuInflater inflater = getMenuInflater();
int tab = getTabHost().getCurrentTab();
switch (tab) {
...
}
return true;
}
The problem is that I don’t know what to put in the switch statement. More specifically, I don’t know how to compare “tab”, which is an integer corresponding to the currently selected tab, to an enum element.
You can add a method as below in your mTab enum –
and then in your onPrepareOptionsMenu() you can do like this 0