简体   繁体   中英

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

I have no idea why i am getting this exception.

Here is my code -

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>

I am including this layout in my xml file -

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

And then i am using following code in my 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);
        }

The exception is coming at following line -

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

I had checked the imports and they all are right and i am using support library.

Replace you code :

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

with:

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

You made a mistake on the id, R.id.photoGalleryToolbar is the root view of the layout which you include here is the AppBarLayout . The Toolbar 's id is R.id.toolbar you defined in the toolbar.xml .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM