5

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)
4

2 回答 2

1

此问题现已修复ViewPager2

你需要使用Version 1.0.0-beta03

更新dependencies_ViewPager2

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

Bug修复

  • 修复了瞬态 Fragment 状态的 FragmentStateAdapter 问题。b/134246546
于 2019-08-08T04:33:18.230 回答
1

我找到了解决方案。显然,您必须在其他配置更改后恢复 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()
        ...
}
于 2019-08-05T05:40:25.303 回答