ViewPager2+Fragment+FragmentStateAdapter遇到系统主题更换时Fragment数据丢失

1. 问题描述:

  在ViewPager 设置壁纸,导致Activity 获取Fragment 数据丢失 

2. 解决方案:  

  设置 vp.isSaveEnabled = false   ,设置不保存,在适配器中销毁item 

  引发问题:vp 重建之后,会丢失之前所在的位置

  解决方案:Activity onSaveInstanceState 中保存数据,在 onRestoreInstanceState  中恢复状态

3. 代码实现:

在Activity :    
    vp.isSaveEnabled = false


    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        mStep = savedInstanceState?.getInt("mStep", mStep)
        if (mStep == STEP2) {
            step(STEP2)
        } else if (mStep == STEP3) {
            step(STEP3)
        }
        LogUtils.i("onRestoreInstanceState mStep=$mStep")
    }

    override fun onSaveInstanceState(outState: Bundle) {
        outState.putInt("mStep", mStep)
        super.onSaveInstanceState(outState)
    }

适配器:
/**
 * 通用Fragment 适配器
 */
class SimpleFragmentStateAdapter(activity: FragmentManager, val fragments: List<Fragment>) :
    FragmentStatePagerAdapter(activity) {

    override fun getCount(): Int {
        return fragments.size
    }

    override fun getItem(position: Int): Fragment {
        return fragments[position]
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val mFragments = javaClass.superclass?.getDeclaredField("mFragments")
        mFragments?.isAccessible = true
        (mFragments?.get(this) as ArrayList<*>?)?.clear()

        val mSavedState = javaClass.superclass?.getDeclaredField("mSavedState")
        mSavedState?.isAccessible = true
        (mSavedState?.get(this) as ArrayList<*>?)?.clear()
        return super.instantiateItem(container, position)
    }

}

  

参考致谢:

Android ViewPager2+Fragment+FragmentStateAdapter遇到系统主题更换时Fragment数据丢失

Android ViewPager+Fragment遇到系统主题更换时Fragment不正常刷新

 

posted @ 2023-04-20 16:52  紫虹在雪  阅读(470)  评论(0编辑  收藏  举报