首页 > 解决方案 > ClassCastException:Fragment1 无法转换为 Fragment2

问题描述

我正在开发一个带有 BottomNavigationBar 和 FrameLayout 的 Android 应用程序。对于 BottomNavBar 的每个项目,我都有不同的片段。我正在尝试使用 Fragment2 fragmentClass = (Fragment2) getSupportFragmentManager().findFragmentById(R.id.fragLayout); (fragLayout 是我的 FrameLayout 的 ID)将数据从我的 MainActivity 发送到其中一个片段。

但是当我运行我的项目时,我在 LogCat 中收到以下错误:

.ClassCastException:com.example.Fragment1 无法转换为 com.example.Fragment2

我究竟做错了什么?当这段代码运行时, Fragment2 是活动的,那么为什么它说它不能被强制转换为 Fragment2 呢?

标签: javaandroidandroid-fragments

解决方案


经过几个小时的搜索,我找到了解决问题的方法。我只是用 Fragment2 fragmentTwoClass = (Fragment2) fm.getFragments().get(1); 而不是 Fragment2 fragmentTwoClass = (Fragment2) fm.getFragmentById(R.id.fragLayout);


推荐阅读