android – 如何在UI设置时获取ActionBar菜单?

前端之家收集整理的这篇文章主要介绍了android – 如何在UI设置时获取ActionBar菜单?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
出于某种原因,onCreateOptionsMenu()在我的应用程序中被称为AFTER onResume()…因此,当我设置我的UI(在onCreate()和onResume()之间时,我无法得到菜单),导致无法为我的ActionBar设置相应的操作项…

到目前为止,我发现的唯一解决方法是在onCreate()返回之前手动调用invalidateOptionsMenu();那样onCreateOptionsMenu()立即被调用,我得到一个菜单,然后我终于可以添加所需的操作项.

有没有人遇到过这个问题?在onResume()之后调用onCreateOptionsMenu()时,你应该如何以编程方式设置你的动作项?

我的应用程序在JellyBean上运行,它使用内置的ActionBar(没有ActionBarSherlock),android:minSdkVersion =“14”和android:targetSdkVersion =“16”

解决方法

首先考虑一下,也许你不应该这样做.听起来您的想法可能违反 Android的典型设计模式.例如,如果您的菜单正在响应用户选择而发生变化,则应使用上下文操作模式.

>从Action Bar API Guide

As a general rule,all items in the options menu (let alone action items) should have a global impact on the app,rather than affect only a small portion of the interface. […] So,even before deciding whether a menu item should appear as an action item,be sure that the item has a global scope for the current activity.

>从Menu API Guide开始:

You should never change items in the options menu based on the View currently in focus. When in touch mode (when the user is not using a trackball or d-pad),views cannot take focus,so you should never use focus as the basis for modifying items in the options menu. If you want to provide menu items that are context-sensitive to a View,use a 07002.

除非您确实想要更改菜单项,否则应在onPrepareOptionsMenu()中进行更改.当发生需要更改菜单项的事件时,将相关信息放入字段并调用invalidateOptionsMenu().覆盖onPrepareOptionsMenu()并检查字段的值以确定要添加/删除菜单项.

(它也可以调用invalidateOptionsMenu()并覆盖onCreateOptionsMenu()来修改应该显示哪些菜单项,尽管不推荐这种方法.)

更多来自Menu API Guide

You should use onCreateOptionsMenu() only to create the initial
menu state and not to make changes during the activity lifecycle.
If you want to modify the options menu based on events that occur
during the activity lifecycle,you can do so in the
onPrepareOptionsMenu() method.

This method passes you the Menu object as it currently exists so you
can modify it,such as add,remove,or disable items. (Fragments also
provide an onPrepareOptionsMenu() callback.)

  • On Android 2.3.x and lower,the system calls onPrepareOptionsMenu()
    each time the user opens the options menu (presses the Menu button).

  • On Android 3.0 and higher,the options menu is considered to always be
    open when menu items are presented in the action bar. When an event
    occurs and you want to perform a menu update,you must call
    invalidateOptionsMenu() to request that the system call
    onPrepareOptionsMenu().

原文链接:https://www.f2er.com/android/309490.html

猜你在找的Android相关文章