java.lang.ClassCastException: androidx.appcompat.app.ToolbarActionBar cannot be...
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.
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
想把上面的改成自定义的toolbar
其中有几个改动是:
- 移除了主题默认的工具栏
在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>
- 加入自己的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
问题就出在toolbar = appCompactActivity.supportActionBar as Toolbar
在Google上搜索一番之后,多半回答都比较久远了,都是引入的包的版本不对什么的。
其实我们这边只用把toolbar = appCompactActivity.supportActionBar as Toolbar
改成toolbar = appCompactActivity.toolbar
即可。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK