6

java.lang.ClassCastException: androidx.appcompat.app.ToolbarActionBar cannot be...

 1 year ago
source link: https://www.daozhao.com/10841.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

java.lang.ClassCastException: androidx.appcompat.app.ToolbarActionBar cannot be cast to androidx.appcompat.widget.Toolbar

如果您发现本文排版有问题,可以先点击下面的链接切换至老版进行查看!!!

java.lang.ClassCastException: androidx.appcompat.app.ToolbarActionBar cannot be cast to androidx.appcompat.widget.Toolbar

最近看《android权威指南》的时候,看到里面提到了自定义toolbar

file

想把上面的改成自定义的toolbar

file

其中有几个改动是:

  1. 移除了主题默认的工具栏

在manifest里面加入了android:theme="@style/NoActionBarTheme"

<activity
    android:name="com.daozhao.hello.activity.CriminalActivity"
    android:theme="@style/NoActionBarTheme"
    android:exported="true"
    android:label="@string/crime">
</activity>

在strings.xml中加入了NoActionBarTheme

<style name="NoActionBarTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
</style>
  1. 加入自己的Toolbar

在fragment的xml文件中加入了androidx.appcompat.widget.Toolbar

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</androidx.appcompat.widget.Toolbar>

在fragment的onAttach的时候加入

val appCompactActivity = requireActivity() as AppCompatActivity

toolbar = appCompactActivity.supportActionBar as Toolbar;

但是在运行过程中出现了报错 java.lang.ClassCastException: androidx.appcompat.app.ToolbarActionBar cannot be cast to androidx.appcompat.widget.Toolbar

file

问题就出在toolbar = appCompactActivity.supportActionBar as Toolbar

在Google上搜索一番之后,多半回答都比较久远了,都是引入的包的版本不对什么的。

file

其实我们这边只用把toolbar = appCompactActivity.supportActionBar as Toolbar改成toolbar = appCompactActivity.toolbar即可。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK