简体   繁体   中英

cannot be cast to androidx.appcompat.widget.Toolbar

My app crashes whenever I launch this activity and throws the error :

Caused by: java.lang.ClassCastException: android.widget.Toolbar cannot be cast to androidx.appcompat.widget.Toolbar

Below is my code, how can I fix this?

package com.example.irecipe;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.os.Bundle

import android.widget.TextView;

public class RecipeActivity extends AppCompatActivity {

    Toolbar toolbar;
    TextView toolbar_title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe);

        toolbar = (androidx.appcompat.widget.Toolbar) findViewById(R.id.toolBar);
        setSupportActionBar(toolbar);

        toolbar_title = findViewById(R.id.toolBar_title);
        toolbar_title.setText("Recipe");

    }

}

XML for Toolbar

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white_grey"
    android:minHeight="?attr/actionBarSize"
    app:menu="@menu/menu_top_right"
    app:titleTextColor="@android:color/white"/>

Java Code for Toolbar

Toolbar toolbar;
toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    if (getSupportActionBar() != null) {
        getSupportActionBar().setTitle("");
    }

Hope this will work for you and Its tested and working properly for me.

Change this:

toolbar = (androidx.appcompat.widget.Toolbar) findViewById(R.id.toolBar);

to:

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

从行中删除(androidx.appcompat.widget.Toolbar)toolbar = (androidx.appcompat.widget.Toolbar) findViewById(R.id.toolBar)

Just remove this (androidx.appcompat.widget.Toolbar) , so it will be like toolbar = findViewById(R.id.toolBar); .

Caused by: java.lang.ClassCastException: android.widget.Toolbar cannot be cast to androidx.appcompat.widget.Toolbar

I've 2 solutions you can try:

  1. Change the import of import androidx.appcompat.widget.Toolbar to import android.widget.Toolbar and remove the casting, toolbar = findViewById(R.id.toolBar);
  2. change the layout implementation of <android.widget.Toolbar... to androidx.appcompat.widget.Toolbar...

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