Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...