How to Dynamically Add Menu Items to an Android Activity
public class yourActivity extends Activity {
...
private static final int MENU_ADD = Menu.FIRST;
private static final int MENU_LIST = MENU.FIRST + 1;
private static final int MENU_REFRESH = MENU.FIRST + 2;
private static final int MENU_LOGIN = MENU.FIRST + 3;
/**
* Use if your menu is static (i.e. unchanging)
*/
/*
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_ADD, Menu.NONE, R.string.your-add-text).setIcon(R.drawable.your-add-icon);
menu.add(0, MENU_LIST, Menu.NONE, R.string.your-list-text).setIcon(R.drawable.your-list-icon);
menu.add(0, MENU_REFRESH, Menu.NONE, R.string.your-refresh-text).setIcon(R.drawable.your-refresh-icon);
menu.add(0, MENU_LOGIN, Menu.NONE, R.string.your-login-text).setIcon(R.drawable.your-login-icon);
return true;
}
*/
/**
* Gets called every time the user presses the menu button.
* Use if your menu is dynamic.
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if(enableAdd)
menu.add(0, MENU_ADD, Menu.NONE, R.string.your-add-text).setIcon(R.drawable.your-add-icon);
if(enableList)
menu.add(0, MENU_LIST, Menu.NONE, R.string.your-list-text).setIcon(R.drawable.your-list-icon);
if(enableRefresh)
menu.add(0, MENU_REFRESH, Menu.NONE, R.string.your-refresh-text).setIcon(R.drawable.your-refresh-icon);
if(enableLogin)
menu.add(0, MENU_LOGIN, Menu.NONE, R.string.your-login-text).setIcon(R.drawable.your-login-icon);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case MENU_ADD: doAddStuff(); break;
case MENU_LIST: doListStuff(); break;
case MENU_REFRESH: doRefreshStuff(); break;
case MENU_LOGIN: doLoginStuff(); break;
}
return false;
}
The following specific example adds a MENU_LOGOUT option if the user is logged in.
private static final int MENU_LOGOUT = MENU.FIRST + 4;
public boolean onPrepareOptionsMenu(Menu menu) {
...
if(auth.isLoggedIn()) {
menu.add(0, MENU_LOGOUT, Menu.NONE, R.string.your-logout-text).setIcon(R.drawable.your-logout-icon);
}
...
}
public boolean onOptionsItemSelected(MenuItem item) {
...
case MENU_LOGOUT:
if(auth.isLoggedIn()) {
doLogout();
} else {
Toast.makeText(this, "You must have somehow been logged out between the time the menu button was pressed and now.", Toast.DURATION_LONG).show();
}
break;
...
}
That's all there is to it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…