为什么 findViewById(R.android.id.home) 总是返回 null? [英] Why does findViewById(R.android.id.home) always return null?

查看:37
本文介绍了为什么 findViewById(R.android.id.home) 总是返回 null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 AppCompat 并尝试调用属于工具栏的向上/后退按钮的 ImageView.

I'm using AppCompat and trying to recall the ImageView for the up/back button belonging to the toolbar.

我知道 R.android.id.home 存在,因为我可以将其点击作为菜单项进行管理:

I know R.android.id.home exists, because I can manage its click as a Menu item:

public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
         //this works
    }
    return super.onOptionsItemSelected(item);
}

除此之外,每当我尝试调用 findViewById(android.R.id.home) - 无论是 onCreate,还是 onClick> 自定义按钮 - 我得到空值.如果在上面的示例中调用 findViewById(item.getItemId()),我什至得到 null.

Apart from that, whenever I try to call findViewById(android.R.id.home) - be it onCreate, be it onClick of a custom button - I get null. I even get null if, in the sample above, I call findViewById(item.getItemId()).

这是为什么?这个问题在这里之前已经被问过,大多数时候是关于 ActionBarSherlock(我没有使用).另一次建议使用:

Why is it? This question has been asked before here, most times regarding ActionBarSherlock (which I am not using). Another time it was suggested to use:

getWindow().getDecorView().findViewById(android.R.id.home)

但它不起作用.在那个问题中,OP 还说 findViewById(android.R.id.home) 适用于 API>3.0,但这对我来说不是真的.有什么想法吗?

But it isn't working. In that question the OP also says findViewById(android.R.id.home) works on API>3.0, but that's not true for me. Any ideas?

推荐答案

home"图标是否是一个widget,它是什么类的widget,它的ID是什么(如果有的话),取决于动作条的执行.对于不同的 API 级别,本机操作栏可能会以不同的方式执行此操作,并且所有这些都可能与 appcompat-v7 执行此操作的方式不同.更不用说 ActionBarSherlock 或其他操作栏实现了.

Whether or not the "home" icon is a widget, and what class of widget it is, and what its ID is (if any), is up to the implementation of the action bar. The native action bar may do this differently for different API levels, and all of that may be different than the way appcompat-v7 does it. Let alone ActionBarSherlock or other action bar implementations.

具体来说,android.R.id.home 是一个菜单 ID,这就是为什么你可以在像 onOptionsItemSelected() 这样的地方使用它.它不一定是小部件 ID,这就是为什么它可能会或可能不会与 findViewById() 一起使用.

Specifically, android.R.id.home is a menu ID, which is why you can use it in places like onOptionsItemSelected(). It is not necessarily a widget ID, which is why it may or may not work with findViewById().

理想情况下,您不要试图弄乱不是您自己构建的 UI 的内部实现.

Ideally, you do not attempt to mess with the internal implementation of a UI that you did not construct yourself.

真的需要自己制作向上按钮来设计样式吗?

do one really has to make his own Up button to style it?

我不知道,因为我从来没有尝试过设计它.

I do not know, as I have never tried to style it.

这篇关于为什么 findViewById(R.android.id.home) 总是返回 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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