Android开发ClassCastException:AppBarLayout无法转换为Toolbar问题求助
问题根因
- 你在
activity_sheet.xml中给<include>标签设置的id@+id/toolSheet,会覆盖被引入布局toolbar.xml根节点的原有id,所以调用findViewById(R.id.toolSheet)返回的是toolbar.xml根节点AppBarLayout的实例 - 代码中将该
AppBarLayout实例直接强转为Toolbar类型,触发了报错日志中的ClassCastException类型转换异常
解决方案
可选两种方案任意一种即可:
方案1:调整控件查找逻辑
修改SheetActivity的setToolbar方法,先获取AppBarLayout实例,再查找其内部的Toolbar:
private void setToolbar() { // 先拿到引入的AppBarLayout实例 AppBarLayout appBarLayout = findViewById(R.id.toolSheet); // 从AppBarLayout内部查找Toolbar toolbar = appBarLayout.findViewById(R.id.toolbar); TextView title = toolbar.findViewById(R.id.title_toolbar); TextView subtitle = toolbar.findViewById(R.id.subtitle_toolbar); ImageButton back = toolbar.findViewById(R.id.back); ImageButton save = toolbar.findViewById(R.id.save); title.setText("Attendance Sheet"); subtitle.setVisibility(View.GONE); back.setVisibility(View.INVISIBLE); save.setVisibility(View.INVISIBLE); }
方案2:直接通过Toolbar自身id查找
Toolbar在toolbar.xml中已经设置了独立id@+id/toolbar,直接全局查找即可:
private void setToolbar() { // 直接查找布局内的Toolbar实例 toolbar = findViewById(R.id.toolbar); TextView title = toolbar.findViewById(R.id.title_toolbar); TextView subtitle = toolbar.findViewById(R.id.subtitle_toolbar); ImageButton back = toolbar.findViewById(R.id.back); ImageButton save = toolbar.findViewById(R.id.save); title.setText("Attendance Sheet"); subtitle.setVisibility(View.GONE); back.setVisibility(View.INVISIBLE); save.setVisibility(View.INVISIBLE); }
额外优化建议
你当前toolbar.xml中AppBarLayout的高度设置为match_parent,会占满整个父布局的高度,修改为wrap_content更符合Toolbar的使用场景:
<?xml version="1.0" encoding="utf-8"?> <com.google.android.material.appbar.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- 原有内部布局不变 --> </com.google.android.material.appbar.AppBarLayout>
内容的提问来源于stack exchange,提问作者Pranay Sadani
相关产品推荐
相关产品推荐

