【问题标题】:Icons on ToolBar Not Responding When Navigation Drawer Added添加导航抽屉时工具栏上的图标没有响应
【发布时间】:2016-01-04 19:38:08
【问题描述】:

我在我的活动中添加了一个导航抽屉,它似乎工作正常。问题是我的工具栏上有另一个名为 info 的图标,现在没有响应。此信息项存在于我的 menu.xml 文件中:

    <item
    android:id="@+id/info"
    android:title="Info"
    android:icon="@drawable/ic_info_outline_black_24dp"
    android:orderInCategory="100"
    app:showAsAction="always" />

我在我的 Java 代码中扩展了这个菜单:

    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.action_bar_items, menu);
    return true;
}

并将其添加到我的 onOptionsItemsSelectedMethod 中,其中还包含我的导航抽屉:

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.home:{
            if (drawerLayout.isDrawerOpen(drawerList)){
                drawerLayout.closeDrawer(drawerList);
            }else{
                drawerLayout.openDrawer(drawerList);
            }
            return true;
        }case R.id.info:{
            Toast.makeText(getApplicationContext(),"HEY",Toast.LENGTH_LONG).show();
        }
        default:return super.onOptionsItemSelected(item);
    }
}

图标在我的工具栏上弹出,但当我单击它时没有响应。请帮忙。谢谢。

【问题讨论】:

    标签: android


    【解决方案1】:

    ID 需要保持一致

    xml 你有:

    android:id="@+id/infoActionBar"
    

    java 代码中,您正在寻找:

    case R.id.info:
    

    更改其中任何一个,以与另一个匹配。

    编辑:case R.id.home: 替换为case android.R.id.home:

    【讨论】:

    • 刚刚改了。还是什么都没有
    • @MarkF 我在一个项目中使用了您代码的所有三个 sn-ps,并且正确显示了 toast。可能需要更多信息来解决您的问题。此外,您可能希望将 case R.id.home: 替换为 case android.R.id.home:
    • 是的,就是这样。这个案子没有被使用。谢谢。
    • @MarkF 我相应地更新了答案,如果它为您解决了问题,您可以选择它作为正确答案:)
    【解决方案2】:

    您的 xml 中的信息按钮 ID 是 android:id="@+id/infoActionBar",您尝试调用 case R.id.info:,因此请更改其中一个并重试 :)

    infoActionBar vs info

    【讨论】:

      【解决方案3】:

      onOptionsItemSelecteditem.getItemId()的情况下必须是项目的id而不是标题

      @Override 
      public boolean onOptionsItemSelected(MenuItem item) {
          switch (item.getItemId()){
              case R.id.home:{
                  if (drawerLayout.isDrawerOpen(drawerList)){ 
                      drawerLayout.closeDrawer(drawerList); 
                  }else{ 
                      drawerLayout.openDrawer(drawerList); 
                  } 
                  return true; 
              }case R.id.infoActionBar:{
                  Toast.makeText(getApplicationContext(),"HEY",Toast.LENGTH_LONG).show();
              } 
              default:return super.onOptionsItemSelected(item);
          } 
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-26
        • 2019-09-15
        • 1970-01-01
        • 1970-01-01
        • 2014-12-23
        • 1970-01-01
        • 1970-01-01
        • 2014-12-14
        相关资源
        最近更新 更多