【问题标题】:FragmentStateAdapter crashes, throwing java.lang.IllegalStateExceptionFragmentStateAdapter 崩溃,抛出 java.lang.IllegalStateException
【发布时间】:2021-07-22 13:27:08
【问题描述】:

在我的应用程序中,我有一个带有按钮的 PlaylistMenuFragment,它通过以下方法将 ViewPager 中的自身替换为 PlaylistContentFragment,反之亦然:

fun goToPlaylistContent() {
    pagerAdapter.replaceLastFragmentWith(PlaylistContentFragment())
}

fun goToPlaylistMenu() {
    pagerAdapter.replaceLastFragmentWith(PlaylistMenuFragment())
}

正在调用的适配器方法:

fun replaceLastFragmentWith(newFragment: Fragment) {
    fragmentList[LAST_FRAGMENT_INDEX] = newFragment
    notifyItemChanged(LAST_FRAGMENT_INDEX)
}

如果我单击PlaylistMenuFragment 中的一个按钮,该按钮转到PlaylistContentFragment,执行上述方法,一切正常。但是,如果然后我单击 PlaylistContentFragment 中的一个返回到 PlaylistMenuFragment 的按钮,则应用程序崩溃,并引发以下异常:

java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling androidx.viewpager2.widget.ViewPager2$RecyclerViewImpl{8ebfd7a VFED..... ......ID 0,0-720,1040 #1}, adapter:com.pegoraro.musicast.main.PagerAdapter@a12492b, layout:androidx.viewpager2.widget.ViewPager2$LinearLayoutManagerImpl@e567188, context:com.pegoraro.musicast.main.MainActivity@e8e6424

崩溃可追溯到上述方法。如果我用 try-catch 块将 notifyItemChanged 包装在适配器方法中,则应用程序按预期工作,没有任何问题的迹象,除非我查看 logcat,它仍然显示抛出异常。这是一个肮脏的修复,我不喜欢:

fun replaceLastFragmentWith(newFragment: Fragment) {
    fragmentList[LAST_FRAGMENT_INDEX] = newFragment
    try {
        notifyItemChanged(LAST_FRAGMENT_INDEX)
    } catch (e: Exception) {
        Log.d("TEST", e.toString())
    }
}

我正在尝试在TabLayout 内的这两个片段之间实现一种导航,这就是我设法做到的方式。因此,如果错误来自我如何处理这个问题的基本问题,那么还有什么替代方法?如果不是,问题的原因可能是什么?谢谢。

【问题讨论】:

    标签: android android-viewpager androidx android-tablayout android-viewpager2


    【解决方案1】:

    ViewPager2 适配器上调用任何notifyXX() 方法与RecyclerView 的方法相同,因为ViewPager2 内部函数基于RecyclerView。

    并且由于notifyXX() 方法在后台线程中工作,在您的情况下,这直接影响 ViewPager 当前片段之一;所以你需要在 UI 线程中明确地这样做

    viewpager.post {
        notifyItemChanged(LAST_FRAGMENT_INDEX)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多