A Better ‘More’ Menu Option For Android Menus

So our new ‘more’ button works now.  When you press it, the small menu is replaced with one that has more buttons.  However, those buttons don’t do anything, do they?  Any why is that?

Better Android Menu Expanded

Better Android Menu Expanded

There is a simple reason: the menu button listener was created to listen only for the original three buttons.  When the buttons are pressed, the app doesn’t know to do anything with them.

You can of course have the buttons do whatever you want them to do…I’ll leave that up to you.  What I will have all of the buttons do when clicked is restore the menu back to its default condition.   So first we will define a function that will clear the menu and repopulate it with the original three buttons.

public void restoreMenu(){
 mmenu.close();
 mmenu.clear();
 mmenu.add(0, R.id.settingsb, 1, getString(R.string.settings_name)).setIcon(R.drawable.ic_menu_settings);
 mmenu.add(0, R.id.exitb, 2, getString(R.string.exit)).setIcon(R.drawable.ic_menu_exit);
 mmenu.add(0, R.id.moreb, 3, getString(R.string.more)).setIcon(R.drawable.ic_menu_more);
}

This function is of course very similar to expandMenu().  It closes the menu, clears it out, then adds the buttons in order.  Notice that we don’t bother to open the menu when we are done; there isn’t any need to reopen the menu since the behavior of the pressed button should be taking over and we are now done with the menu.

The final thing to do then is to update the menu button listener so that it listens to all of our buttons.  Replace the original listener with this, and of course fill in your own functions as needed:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
 switch (item.getItemId()) {
 case R.id.reloadb:
 stopAlert();
 break;
 case R.id.newsb:
 restoreMenu();
 break;
 case R.id.tipsb:
 restoreMenu();
 break;
 case R.id.aboutb:
 restoreMenu();
 break;
 case R.id.demob:
 restoreMenu();
 break;
 case R.id.settingsb:
 Intent sintent = new Intent(this, PrefsActivity.class);
 startActivity(sintent);
 restoreMenu();
 break;
 case R.id.moreb:
 expandMenu();
 break;
 case R.id.exitb:
 restoreMenu();
 finish();
 break;
 }
 return true;
}

No matter how many menus you make, just remember to include a case for every possible button in the menu listener.

There!  Now you have built your own improved ‘more’ menu option.  Using this method you can nest these as deep as you need, or have whatever sub-menus work best for the interface your app requires.

Do you have suggestions on how to improve this idea?  Please feel free to leave them in the comments below!

Cody (17 Posts)