MenuItem的findViewById返回null [英] findViewById for MenuItem returns null

查看:119
本文介绍了MenuItem的findViewById返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用于ActionBar菜单的xml文件。

This is my xml file for the ActionBar menu.

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
            android:id="@+id/fav_button"
            android:title="Favourite"
            android:icon="@drawable/unstar"
            android:showAsAction="always|withText" />
</menu>

在我的 onCreate 函数中, 之后,调用 setContentView 。我做 favButton =(MenuItem)this.findViewById(R.id.fav_button); 但这返回null。

In my onCreate function, after calling setContentView. I do favButton = (MenuItem) this.findViewById(R.id.fav_button); But this returns null.

但是在 onOptionsItemSelected 函数上返回正确的对象。

But returns the proper object on the onOptionsItemSelected function.

我正在使用ActionBarSherlock,如果这样做会导致

I'm using ActionBarSherlock, if that would make a difference.

我尝试了其他findViewById建议的各种选项,它们返回空问题,但它们没有解决我的问题。

I have tried various options suggested by other findViewById returns null questions, but they haven't solved my issue.

推荐答案

而不是

favButton = (MenuItem) this.findViewById(R.id.fav_button);  

在getMenuInflater()。inflate(R.menu.activity_main,menu)之后的onCreateOptionsMenu中;

in onCreateOptionsMenu after getMenuInflater().inflate(R.menu.activity_main, menu);

favButton = menu.findItem(R.id.fav_button);

这篇关于MenuItem的findViewById返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆