问题描述
我有一个包含 2 个片段的 Activity.两者都是 ListFragments 并且都向 Menu 贡献 MenuItem.我有一个 MenuItem,我已经设置了属性 android:showAsAction 让它在 ActionBar 上显示为一个按钮.哪个工作正常.
I have an Activity that has 2 fragments. Both are ListFragments and both contribute MenuItems to the Menu. I have one MenuItem that I've set the attribute android:showAsAction to have it show as a button on the ActionBar. Which works fine.
现在 MenuItem 依赖于状态.这是用于暂停和恢复队列的暂停/恢复菜单选项.我的问题是我不知道如何在创建 Fragment 时设置它的初始雕像.
Now the MenuItem is state dependent. It's a Pause/Resume menu option for pausing and resuming a queue. My problem is I can't figure out how to set it's initial statue when the Fragment is created.
它的状态取决于队列是否暂停.所以我有一个 AsyncTask 来获取队列并根据队列的状态设置一个布尔值(暂停).我正在调用 onPrepareOptionsMenu 以根据队列的最后一个已知状态设置暂停菜单项的文本,如果我将 MenuItem 留在实际菜单中,这会很好用.你点击菜单图标,onPrepareOptionsMenu 被触发,菜单在显示之前更新.
It's state is dependent on the whether the queue is paused or not. So I have an AsyncTask that gets the queue and sets a boolean (paused) based on the state of the queue. I'm calling onPrepareOptionsMenu to set the text for the Pause menu item based on the last known state of the queue and this works great if I leave the MenuItem in the actual menu. You tap the menu icon and onPrepareOptionsMenu is fired and the menu is updated before it's displayed.
问题是,如果我将相同的 MenuItem 放在 ActionBar (showAsAction) 上,如何强制它更新而不必调用 onPrepareOptionsMenu?我需要能够做到这一点,因为在第一次启动应用程序时,我发送了一个请求来获取队列,但在设置并显示 ActionBar 后任务返回.我在片段中创建了一个处理程序,每次收到队列更新时都会调用该处理程序,但是从那里开始,如何更新 ActionBar 上 MenuItem 的文本?除了 onPrepareOptionMenu 之外,我似乎无法找到一种方法来获取当前设置的菜单来操作它.
The problem is, if I put that same MenuItem on the ActionBar (showAsAction), how can I force it to update without having to call onPrepareOptionsMenu? I need to be able to do this because on first launch of the app, I send a request to get the queue, but the task returns after the ActionBar is setup and displayed. I've created a handler in my fragment that gets called every time I get a queue update, but from there, how can I update the text for my MenuItem on the ActionBar? I can't seem to find a way to get the currently set Menu to manipulate it except for in onPrepareOptionMenu.
罗伯.
推荐答案
选项 #1:尝试 invalidateOptionsMenu()
.我不知道这是否会强制立即重绘操作栏.
Option #1: Try invalidateOptionsMenu()
. I don't know if this will force an immediate redraw of the action bar or not.
选项#2:查看getActionView()
是否为受影响的MenuItem
返回任何内容.showAsAction
可能只是自动为您创建操作视图.如果是这样,您大概可以启用/禁用该 View
.
Option #2: See if getActionView()
returns anything for the affected MenuItem
. It is possible that showAsAction
simply automatically creates action views for you. If so, you can presumably enable/disable that View
.
除了 onPrepareOptionMenu 之外,我似乎无法找到一种方法来获取当前设置的 Menu 来操作它.
您可以保留在 onCreateOptionsMenu()
中传递给您的 Menu
对象.引用文档:
You can hang onto the Menu
object you were handed in onCreateOptionsMenu()
. Quoting the docs:
您可以安全地保留菜单(以及从它创建的任何项目),根据需要对其进行修改,直到下次调用 onCreateOptionsMenu() 为止.
这篇关于如何更新 ActionBar 中显示的菜单项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!