代码之家  ›  专栏  ›  技术社区  ›  Shunan

java.lang.ClassCast异常:android.support.design.widget。AppBarLayout无法强制转换为android.support.v7.widget.Toolbar

  •  0
  • Shunan  · 技术社区  · 10 年前

    我不知道为什么我会得到这个例外。

    这是我的密码-

    工具栏.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"/>
    

    然后我在活动中使用以下代码-

    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);
    

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

    1 回复  |  直到 10 年前
        1
  •  2
  •   L. Swifter    10 年前

    替换您的代码:

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

    使用:

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

    你的身份证弄错了, R.id.photoGalleryToolbar AppBarLayout 这个 Toolbar 的id为 R.id.toolbar toolbar.xml .