【问题标题】:ClassCastException: Fragment1 cannot be cast to Fragment2ClassCastException:Fragment1 无法转换为 Fragment2
【发布时间】:2019-12-14 03:21:45
【问题描述】:

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

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

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

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

【问题讨论】:

  • ... 因为它是Fragment1。我想他们不会处于(有效的)继承关系中。
  • 您何时以及如何切换到Fragment2
  • 当我点击底部导航栏的一个项目时,我正在切换片段。当我点击它时,它会切换片段,然后运行我的代码将数据发送到片段。
  • 所以当你尝试向Fragment2发送数据时你还在onNavigationItemSelected

标签: java android android-fragments


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-02
    • 2016-06-30
    • 2016-01-14
    • 2013-07-25
    • 2016-07-05
    • 2017-01-24
    • 2018-08-03
    • 2016-01-07
    相关资源
    最近更新 更多