道招

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即可。

更新时间:
上一篇:上海市2023年事业单位公开招聘及报名数据统计下一篇:Android在fragment中请求权限后onRequestPermissionsResult没有被执行

相关文章

关注道招网公众帐号
友情链接
消息推送
道招网关注互联网,分享IT资讯,前沿科技、编程技术,是否允许文章更新后推送通知消息。
允许
不用了