首页 > 解决方案 > AppBarLayout 无法转换为 androidx.appcompat.widget.Toolbar

问题描述

我的应用程序在启动时崩溃,这是我得到的错误 com.google.android.material.appbar.AppBarLayout cannot be cast to androidx.appcompat.widget.Toolbar

那是我的 XML 文件

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/mToolBar">
    <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/logo"/>

        <TextView
            android:id="@+id/profileText"
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            android:text="  Hello"
            android:textColor="#000"
            android:textSize="24sp"
            android:textStyle="italic|bold" />
    </androidx.appcompat.widget.Toolbar>

    <com.google.android.material.tabs.TabLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/tabLayout"
        app:tabTextColor="#000"
        app:tabSelectedTextColor="#fff"/>
</com.google.android.material.appbar.AppBarLayout>

<androidx.viewpager.widget.ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/viewPager"/>

我被定向到这行代码mToolBar = findViewById(R.id.mToolBar);

我试图将<androidx.appcompat.widget.Toolbar更改 为<android.widget.Toolbar 并且它没有工作 idk 有什么解决方案请帮帮我

标签: androidxmlmaterial-design

解决方案


如果您想获得对您的引用Toolbar,您需要将您的移动android:id="@+id/mToolBar"到您的Toolbar并将其从您的AppBarLayout.

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/mToolBar"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

推荐阅读