【问题标题】:Can't find Toolbar in an included layout在包含的布局中找不到工具栏
【发布时间】:2015-10-13 01:23:52
【问题描述】:

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

<?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>

我在布局中的&lt;include&gt; 中使用它:

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

然后我引用ToolbarTextView 来设置文本:

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

如果我从&lt;include&gt; 标记中删除id 属性,那么一切正常。

【问题讨论】:

    标签: android android-layout android-toolbar


    【解决方案1】:

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

    如果您将 id 保留在包含标记中,则使用以下代码访问您的工具栏:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多