默认使用的菜单例子都是创建的静态菜单,在某些时候会不方便,比如:

一篇文章的显示,按menu有加入收藏的功能,那实现的是如果未加入收藏,则是加入收藏的操作,否则是取消收藏的操作。

但onCreateOptionsMenu是实现不了这个功能的,它只会运行一次,如果再次按下menu,则不会变化。
我们看看程序说明:

引用
public boolean onCreateOptionsMenu (Menu menu)
Initialize the contents of the Activity's standard options menu. You should place your menu items in to menu.

This is only called once, the first time the options menu is displayed. To update the menu every time it is displayed, see onPrepareOptionsMenu(Menu).

The default implementation populates the menu with standard system menu items. These are placed in the CATEGORY_SYSTEM group so that they will be correctly ordered with application-defined menu items. Deriving classes should always call through to the base implementation.

You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.

When you add items to the menu, you can implement the Activity's onOptionsItemSelected(MenuItem) method to handle them there.

Parameters
menu  The options menu in which you place your items.

Returns
You must return true for the menu to be displayed; if you return false it will not be shown.
See Also
onPrepareOptionsMenu(Menu)
onOptionsItemSelected(MenuItem)


也就是说明了它是第一次显示菜单时调用的,每次更新,需要定义onPrepareOptionsMenu

引用
public boolean onPrepareOptionsMenu (Menu menu)
Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.

The default implementation updates the system menu items based on the activity's state. Deriving classes should always call through to the base class implementation.


比如我这里可以这样处理:

//code from www.aslibra.com
public boolean onPrepareOptionsMenu(Menu menu) {
  menu.clear();
  if(isFavoutite){
    menu.add(0, NFav_ID, 0, R.string.menu_not_favourite).setIcon(R.drawable.ic_tab_selected_contacts);
  }else{
    menu.add(0, Fav_ID, 0, R.string.menu_favourite).setIcon(R.drawable.ic_tab_selected_contacts);
  }
  menu.add(0, Del_ID, 0, R.string.menu_delete).setIcon(R.drawable.ic_tab_selected_contacts);
  return super.onPrepareOptionsMenu(menu);
}


先清空菜单设置,然后根据是否收藏放置第一个选项,再增加删除菜单,完事!


原创内容如转载请注明:来自 阿权的书房
收藏本文到网摘
Tags:
发表评论
表情
emotemotemotemotemotemotemotemotemotemotemotemotemot
emotemotemotemotemotemotemotemotemotemotemotemot
打开HTML 打开UBB 打开表情 隐藏
昵称   密码   游客无需密码
网址   电邮   [注册]
               

验证码 不区分大小写
 

阅读推荐

服务器相关推荐

开发相关推荐

应用软件推荐