簡體   English   中英

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

我不知道為什么我要得到這個例外。

這是我的代碼-

工具欄

<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"/>

然后我在活動中使用以下代碼-

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是布局的根視圖,其中包括AppBarLayout Toolbar的ID是R.id.toolbar您在定義toolbar.xml

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM