如何更改 FragmentStatePagerAdapter 的 getItem 内的片段

How to change fragment inside getItem of FragmentStatePagerAdapter

我有这段代码,我希望 FragmentStatePageAdapter 的第一个片段(在 viewpager 内)根据一些布尔值进行更改。

inner class MainFragmentAdapter(fragmentManager: FragmentManager) :
        FragmentStatePagerAdapter(fragmentManager) {

    override fun getCount(): Int {
        return MainView.Fragments.values().size
    }

    override fun getItem(position: Int): Fragment? {
        return when (position) {
            0 -> {
                if (booleanOne && !booleanTwo) {
                    FragmentOne.newInstance()
                } else if (booleanTwo && !booleanOne) {
                    FragmentTwo.newInstance()
                } else {
                    FragmentThree.newInstance()
                }
            }
            else -> null
        }
    }
}

到目前为止,我找到的唯一解决方案是当我个人知道其中一个布尔值发生变化时,我只是做了类似的事情:

   _fragmentAdapter = MainFragmentAdapter(getLifecycleFragmentManager())

   fragmentViewPager.adapter = _fragmentAdapter

所以我再次设置了适配器,但我觉得这样做不太合适。我不能强制它再次计算 getItem 吗?

在您的 class 中进行这些更改,notifyDataSetChanged() 然后覆盖 getItemPosition() ,它将在每次通知时调用,然后 return 相应的常量,POSITION_NONE 如果您想查看新的更改,否则 POSITION_UNCHANGED

    inner class MainFragmentAdapter(fragmentManager: FragmentManager) :
        FragmentStatePagerAdapter(fragmentManager) {

    override fun getCount(): Int {
        return MainView.Fragments.values().size
    }

    override fun getItem(position: Int): Fragment? {
        return when (position) {
            0 -> {
                if (booleanOne && !booleanTwo) {
                    FragmentOne.newInstance()
                } else if (booleanTwo && !booleanOne) {
                    FragmentTwo.newInstance()
                } else {
                    FragmentThree.newInstance()
                }
               notifyDataSetChanged();
            }
            else -> null
        }
    }

    override fun getItemPosition(@NonNull `object`: Any): Int {
            // this method will be called for every fragment in the ViewPager
            return if (`object` is FragmentOne) {
                POSITION_UNCHANGED // don't force a reload
            } else {
                // POSITION_NONE means something like: this fragment is no longer valid
                // triggering the ViewPager to re-build the instance of this fragment.
                POSITION_NONE
            }
        }

}