【问题标题】:MenuItem's onclick method is not called if menu item showAsAction="always"如果菜单项 showAsAction="always" 则不调用 MenuItem 的 onclick 方法
【发布时间】:2015-09-30 06:47:16
【问题描述】:

菜单项有问题。

我的菜单中有一个搜索视图,我在onPrepareOptionsMenu 中的项目上设置了OnMenuItemClickListener

和我的菜单 xml:showAsAction 属性设置为 "always"

但是,如果我点击搜索图标,什么都没有发生,toast 没有出现。

奇怪的是,如果我设置了 showAsAction="always|collapseActionView",如果会起作用,但搜索图标不见了,取而代之的是“搜索”文本。

成功了,吐司显示出来了。

但图标不见了

************************编辑****************************** **************

【问题讨论】:

  • 另外你能告诉我这是一个工具栏还是android提供的默认操作栏?
  • 看看编辑。

标签: android menuitem android-menu


【解决方案1】:

您的菜单使用了错误的语法。请用这个替换你的菜单充气器/处理程序代码。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.yourActivity_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.search) {
        //Handle the onClick with Toast over here.
        //IF you have multiple options then replace if with a switch() statement
        return true;
    }

    return super.onOptionsItemSelected(item);
}

就图标而言,您已通过添加 android:icon="@drawable/YOU_ICON_HERE" 在 xml 文件中指定图标属性

编辑:看看这个http://developer.android.com/training/search/setup.html 你应该保持 android:showAsAction="collapseActionView|ifRoom" 让它工作。您现在必须做的唯一更改是向 xml 添加一个 android:icon 属性

<item android:id="@+id/search"
      android:title="@string/search_title"
      android:icon="@drawable/ic_search"
      android:showAsAction="collapseActionView|ifRoom"
      android:actionViewClass="android.widget.SearchView" />

或 android.widget.v7 支持取决于您希望支持的 android 版本

【讨论】:

  • 嗨 Varun,我使用工具栏替换了默认操作栏。我试过你的方法,但它也不起作用......根本没有调用 onOptionsItemSelected() 方法。是因为我用了工具栏吗?
  • 工具栏工具栏 = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(工具栏);工具栏.setHomeUpEnabled();添加这些行并向我展示您的 onCreate() 的初始行
  • 嗨 Varun,我已经为这些代码更新了我的帖子。谢谢
  • 添加 if(getSupportActionBar!=null){ setHomeButtonEnabled(true) } 以摆脱空指针错误。它现在工作了吗?您还可以更改初始图标、主页按钮图标、标题并以编程方式添加字幕。
  • 已添加 getSupportActionBar().setHomeButtonEnabled(true);它仍然无法正常工作....
猜你喜欢
  • 2014-04-30
  • 2013-07-28
  • 1970-01-01
  • 2020-09-10
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
  • 2014-06-07
  • 1970-01-01
相关资源
最近更新 更多