我有一个带有四个选项卡的 TabActivity
(每个选项卡都有自己的 Activity)。每个选项卡都定义自己的 onCreateOptionsMenu
(在某些情况下,还定义 onPrepareOptionsMenu
)。加载每个选项卡时,将启动 AsyncTask
以检索填充该选项卡列表所需的数据。
如果我非常快速地在选项卡之间切换(当它们仍在加载时),然后按菜单按钮(当当前选项卡的 AsyncApiTask
仍在运行时),我可以获得错误的选项菜单出现。
例如,假设 FooActivity
(选项卡 1)有一个带有“刷新”项的选项菜单,而 BarActivity
(选项卡 2)有一个带有“查看全部”选项的选项菜单“ 物品。如果我启动应用程序(选项卡 1 处于活动状态),快速切换到选项卡 2,然后点击菜单,有时会显示“刷新”项目(而不是预期的“查看全部”项目)。
此外,虽然这种奇怪的行为有时只发生在第一次按下菜单时(后来按下显示正确的项目),但有时它会“卡住”,并且每次按下都会显示错误的项目,直到我切换选项卡。
知道会发生什么吗?我以前没有听说过这种情况,也找不到任何好的建议。
I have a TabActivity
with four tabs (each is its own Activity). Each tab defines its own onCreateOptionsMenu
(and in some cases, onPrepareOptionsMenu
). When each tab is loaded, an AsyncTask
is kicked off to retrieve the data needed to populate that tab's list.
If I switch between tabs very quickly (while they're still loading) and then press the menu button (while the current tab's AsyncApiTask
is still running), I'm able to get the wrong options menu to appear.
For example, let's say FooActivity
(tab 1) has an options menu with a "Refresh" item, and BarActivity
(tab 2) has an options menu with a "View All" item. If I start the app (with tab 1 active), quickly switch to tab 2, and then hit menu, the "Refresh" item (rather than the expected "View All" item) will sometimes show.
Furthermore, while this weird behavior sometimes occurs just on the first menu press (and later presses show the right items), sometimes it gets "stuck", and the wrong items show up on every press until I switch tabs.
Any idea what could be going on? I haven't heard of this happening before, and haven't been able to find any good suggestions.
发布评论
评论(1)
是的,CommonsWare 的建议是更好的解决方案!您甚至可以考虑使用 FragmentTabHost 和每个选项卡的片段。这样,主机 Activity 就可以从
onTabChanged(String tab)
集中更新选项菜单。虽然
AsyncTask
是从Activity
生成的,但如果它尚未运行onPostExecute(...)
,它仍然会运行。另外,由于AsyncTask
的默认行为是可变的(不同版本的 android 会顺序/并行运行它们),因此如果没有您自己的 ThreadPoolExecutor。您的快速Activity
切换和重复的AsyncTask
似乎正在阻塞。Yes, CommonsWare suggestion is a better solution! You could even consider using FragmentTabHost and fragments for each tab. That way the host activity can update the options menu centrally from
onTabChanged(String tab)
.While an
AsyncTask
is spawned from anActivity
, if it hasn't runonPostExecute(...)
it is still going. Also, since the default behavior ofAsyncTask
s is variable (different versions of android run them sequentially/parallel), it's hard to control without your own ThreadPoolExecutor. Your quickActivity
switching and repeatedAsyncTask
s seem to be blocking.