java - 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 呢?
解决方案
经过几个小时的搜索,我找到了解决问题的方法。我只是用
Fragment2 fragmentTwoClass = (Fragment2) fm.getFragments().get(1);
而不是
Fragment2 fragmentTwoClass = (Fragment2) fm.getFragmentById(R.id.fragLayout);
推荐阅读
- javascript - 我只想取出数字
- python - istitle 使用 def 的问题
- javascript - 使用 ResizeObserver 和媒体查询获得相同的结果
- kubernetes - ISTIO 出口网关流程
- azure-active-directory - 清单中的 Azure AD B2C 应用程序更改显示内部服务器错误
- asp.net - 当前上下文中不存在名称“配置”
- python - Discord.py:我如何让机器人获取在给定时间内对消息做出反应的用户列表
- python - 如何调整条形图的图形间距。Matplotlib
- wordpress - Nginx 反向代理在 Docker 上深度链接 Wordpress
- ruby-on-rails - 用devise使用cancancan时,是否需要将devise添加到capability.rb中?