Skip to content Skip to sidebar Skip to footer

Why Does Findviewbyid(r.android.id.home) Always Return Null?

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 it

Solution 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.

Solution 2:

As CommonsWare said android.R.id.home is a menu ID, not a widget ID. But if you want to access this home button you could do it. For example I needed it to highlight home button in in-app tutorial:

fun AppCompatActivity.getToolbarHomeIcon(): View? =
    this.findViewById<Toolbar?>(R.id.toolbar)?.let { toolbar ->
        val contentDescription: CharSequence = toolbar.navigationContentDescription.let {
            if (it.isNullOrEmpty()) {
                this.getString(R.string.abc_action_bar_up_description)
            } else {
                it
            }
        }
        // Here home button should be created even if it doesn't exist before
        toolbar.navigationContentDescription = contentDescription

        ArrayList<View>().let { potentialViews ->
            toolbar.findViewsWithText(
                potentialViews,
                contentDescription,
                View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION
            )

            potentialViews.getOrNull(0)
        }
    }

Post a Comment for "Why Does Findviewbyid(r.android.id.home) Always Return Null?"