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

android – 如何在UI设置时获取ActionBar菜单?,第1张

概述出于某种原因,onCreateOptionsMenu()在我的应用程序中被称为AFTER onResume()…因此,当我设置我的UI(在onCreate()和onResume()之间时,我无法得到菜单) ,导致无法为我的ActionBar设置相应的 *** 作项… 到目前为止,我发现的唯一解决方法是在onCreate()返回之前手动调用invalidateOptionsMenu();那样onCreate 出于某种原因,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().

总结

以上是内存溢出为你收集整理的android – 如何在UI设置时获取ActionBar菜单?全部内容,希望文章能够帮你解决android – 如何在UI设置时获取ActionBar菜单?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1130267.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存