在包含的布局中找不到工具栏 [英] Can't find Toolbar in an included layout

查看:72
本文介绍了在包含的布局中找不到工具栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Toolbar,里面有一个自定义的TextView:

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>

我在布局的<include>中使用它:

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

然后我引用ToolbarTextView设置文本:

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

我不断收到此错误:

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

如果我从<include>标记中删除了id属性,那么一切都将正常运行.

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

推荐答案

您正在覆盖include标签中的工具栏ID.因此,R.id.toolbar不再是您所包含的活动工具栏的ID,而现在是R.id.app_bar.

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.

如果将ID保留在include标记中,请使用以下代码访问工具栏:

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

这篇关于在包含的布局中找不到工具栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆