java.lang.ClassCastException: android.support.design.widget.AppBarLayout 无法转换为 android.support.v7.widget.Toolbar

java.lang.ClassCastException: android.support.design.widget.AppBarLayout cannot be cast to android.support.v7.widget.Toolbar

我不知道为什么会收到此异常。

这是我的代码 -

toolbar.xml

<android.support.design.widget.AppBarLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:layout_scrollFlags="scroll|enterAlways" />
</android.support.design.widget.AppBarLayout>

我将此布局包含在我的 xml 文件中 -

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

然后我在 activity -

中使用以下代码
Toolbar toolbar = (Toolbar) findViewById(R.id.photoGalleryToolbar);
        setSupportActionBar(toolbar);
        final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeAsUpIndicator(R.drawable.ic_keyboard_backspace_white_24dp);
            actionBar.setDisplayShowTitleEnabled(true);
            actionBar.setTitle("Kidster Photo Gallery");
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

异常出现在下一行 -

Toolbar toolbar = (Toolbar) findViewById(R.id.photoGalleryToolbar);

我检查了导入,它们都是正确的,我正在使用支持库。

替换您的代码:

Toolbar toolbar = (Toolbar) findViewById(R.id.photoGalleryToolbar);

与:

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

您在 id 上输入错误,R.id.photoGalleryToolbar 是您在此处包含的布局的根视图是 AppBarLayoutToolbar 的 ID 是您在 toolbar.xml.

中定义的 R.id.toolbar