onOptionsItemSelected MenuItem View查找

项目中需要对toolbar右边的menu操作,发现点击的时候找不到menu中的view,在网上找了下资料才发现,需要在onCreateOptionsMenu中添加 super.onCreateOptionsMenu(menu),然后在onOptionsItemSelected 中通过findViewById就可以找到menu布局中的view了。

<item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="always"/>

menu中的布局app:showAsAction必须是always,要不然还是为null。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, 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.action_settings) {
        View view = findViewById(R.id.action_settings);
        //这里的view在添加super.onCreateOptionsMenu(menu);后不为null了
        return true;
    }
    return super.onOptionsItemSelected(item);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 11,778评论 0 17
  • 原文地址:http://www.android100.org/html/201606/06/241682.html...
    AFinalStone阅读 4,750评论 0 1
  • 1. Toolbar 1.使用Toolbar,首先需要将系统的ActionBar隐藏,打开res/values/s...
    figure_ai阅读 4,743评论 1 3
  • Toobar与ActionBar 从Android3.0(API level 11)开始,所有使用默认主题的act...
    DoAndKeep阅读 40,848评论 13 81
  • 凌晨三点, 雨好大, 打湿了我抱在坏里的泡面, 最近好像一直都很忙, 并没有留下只言片语, 坚持。
    有童年没青春阅读 1,410评论 0 0