Shubham Nandanwar Shubham Nandanwar - 2 months ago 16
Android Question

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.

Answer

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.