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

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

问题描述

我使用的应用程序兼容性,并试图回忆的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())

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大多数时候被问。 <一href=\"http://stackoverflow.com/questions/16114165/reference-android-r-id-home-on-$p$p-3-0-devices\">Another使用时间有人提出:

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

但它不工作。在这个问题的任择议定书还称 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?

推荐答案

不管是不是家的图标是一个小部件,而它是什么类的小部件,以及它的ID是(如果有的话),达实施行动吧。本机操作栏可以为不同的API层次做到这一点不同,而且所有这一切可能会比路应用程序兼容性-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天全站免登陆