【问题标题】:Hiding actionbar menu items, phone vs. tablet隐藏操作栏菜单项,手机与平板电脑
【发布时间】:2013-11-06 10:19:15
【问题描述】:

我刚刚开始开发一个应用程序,其中包含项目列表和每个项目的详细视图,因此我使用片段设置了不同的手机和平板电脑布局。还有一个导航抽屉,我希望菜单中的一个选项仅在详细视图片段在屏幕上时显示,并在导航抽屉打开时隐藏。所以,我是这样做的:

  1. 主视图创建菜单。
  2. 详细视图片段添加了特定的详细视图选项(共享按钮,“action_share”)。
  3. 打开导航抽屉在导航抽屉片段的 onCreateOptionsMenu 中运行:

    if (menu.findItem(R.id.action_share) != null)
    {
        MenuItem item = menu.findItem(R.id.action_share);
        item.setVisible(false);
        getActivity().invalidateOptionsMenu();
        Toast.makeText(getActivity(), "This works on a tablet.", Toast.LENGTH_SHORT).show();
    }
    else
    {
       Toast.makeText(getActivity(), "...but not on a phone.", Toast.LENGTH_SHORT).show();
    }
    

这在平板电脑上按预期工作,但在手机上未检测到 action_share 菜单项。布局不同如下。

电话:

<DrawerLayout>
    <FrameLayout> <!-- list and detail fragments are swapped in here -->
    <fragment> <!-- navigation drawer -->
</DrawerLayout>

平板电脑:

<DrawerLayout>
   <LinearLayout>
       <fragment> <!-- list fragment -->
       <fragment> <!-- detail fragment -->
   </LinearLayout>
   <fragment> <!-- navigation drawer -->
</DrawerLayout>

层次结构查看器显示的排列略有不同。

电话:

LinearLayout -&gt; ActionBarContainer -&gt; ActionBarView -&gt; ActionMenuView -&gt; ActionMenuItemView (action_share)

平板电脑:

ActionBarOverlayLayout -&gt; LinearLayout -&gt; ActionBarContainer -&gt; ActionBarView -&gt; ActionMenuView -&gt; ActionMenuItemView (action_share)

那么,谁能建议为什么在一种布局中检测到 action_share 菜单项而不是在另一种布局中,以及我可以做些什么来解决这个问题?

编辑:

进一步调查显示menu.findItem() 没有拿起手机上的action_share 菜单项,但findViewById() 是,这很奇怪。当然,我不能对后者做任何事情,因为我不能将它转换为 MenuItem。

【问题讨论】:

    标签: android android-actionbar


    【解决方案1】:

    似乎只有在 onPrepareOptionsMenu 而不是 onCreateOptionsMenu 中才能找到和切换共享按钮的可见性状态的代码。这并不能解释为什么平板电脑布局没有受到影响,但至少两种布局现在都可以正常工作,因为我已经添加了onPrepareOptionsMenu 并将相关代码移至其中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-09
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 1970-01-01
      • 1970-01-01
      • 2013-12-18
      相关资源
      最近更新 更多