Why does findViewById(R.android.id.home) always return null?

随声附和 提交于 2019-12-01 23:22:08

问题


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

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);
}

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()).

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)

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?


回答1:


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.

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().

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.



来源:https://stackoverflow.com/questions/27723266/why-does-findviewbyidr-android-id-home-always-return-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!