Can't find Toolbar in an included layout

I have a Toolbar which has a custom TextView inside:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:background="@drawable/headerbg"
    android:theme="@style/CustomToolbarTheme"
    android:layout_height="48dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toolbar Title"
        android:textColor="@color/white"
        android:textSize="18sp"
        android:fontFamily="sans-serif-light"
        android:layout_gravity="left"
        android:id="@+id/tvToolbarTitle" />

</android.support.v7.widget.Toolbar>

I use it in an <include> in my layout:

<include
        android:id="@+id/app_bar"
        layout="@layout/app_bar" />

I then reference the Toolbar and TextView to set the text:

Toolbar toolbar = (Toolbar) activity.findViewById(R.id.toolbar);
Logger.d(activity.getClass(), "Toolbar: " + toolbar);
TextView tvToolbarTitle = (TextView) toolbar.findViewById(R.id.tvToolbarTitle);
tvToolbarTitle.setText(activity.getTitle());
activity.setSupportActionBar(toolbar);

I keep getting this error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
    'android.view.View android.support.v7.widget.Toolbar.findViewById(int)' on a null object reference

If I remove the id attribute from the the <include> tag, then everything works perfectly.


Solution 1:

You are overriding the id of toolbar in the include tag. So the R.id.toolbar is no longer id of your included toolbar for your activity but now it is R.id.app_bar instead.

If you keep the id in include tag then use following code to access your toolbar:

Toolbar toolbar = (Toolbar) activity.findViewById(R.id.app_bar);