FragmentStateAdapter引发java.lang.IllegalStateException:配置更改后违反了设计假设

时间:2019-08-05 05:04:01

标签: android kotlin android-gradle-plugin android-viewpager2

FragmentStateAdapter引发

  

java.lang.IllegalStateException:违反了设计假设,

旋转设备时。我该如何解决这个问题?

private inner class PagerAdapter : FragmentStateAdapter(this) {
        private val ids = LongSparseArray<Media>()

        override fun getItemCount(): Int = adapter.itemCount

        override fun getItemId(position: Int): Long {
            return adapter.source!![position].time
        }

        override fun containsItem(itemId: Long): Boolean {
            return ids[itemId] != null
        }
    }

例外

 java.lang.IllegalStateException: Design assumption violated.
        at androidx.viewpager2.adapter.FragmentStateAdapter.placeFragmentInViewHolder(FragmentStateAdapter.java:270)
        at androidx.viewpager2.adapter.FragmentStateAdapter.onViewAttachedToWindow(FragmentStateAdapter.java:259)
        at androidx.viewpager2.adapter.FragmentStateAdapter.onViewAttachedToWindow(FragmentStateAdapter.java:68)

2 个答案:

答案 0 :(得分:0)

我找到了解决方案。显然,在其他配置发生更改后,您必须恢复FragmentStateAdapter的状态,以使片段能够正确还原。

保存状态

override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        model.addState(IDS, pagerAdapter.ids)
        model.addState(LIST, (adapter.source as ListAdapterSource).getList())
    }

还原状态

private inner class PagerAdapter : FragmentStateAdapter(this) {
        val ids: LongSparseArray<Media> = model.getState(IDS) ?: LongSparseArray()
        ...
}

答案 1 :(得分:0)

此问题已在ViewPager2

中修复。

您需要使用Version 1.0.0-beta03

更新dependencies中的ViewPager2

 dependencies {
    implementation 'androidx.viewpager2:viewpager2:1.0.0-beta03'
 }
  

错误修复

  • 修复具有临时Fragment状态的FragmentStateAdapter问题。 b/134246546