设备旋转后 ViewPager 无法正常工作

ViewPager is not working correctly after device rotation

旋转后,显示一页旧页,然后显示新页。 轮换前1。 旋转后2.

使用 ViewPager 布局:

<RelativeLayout ...
<androidx.viewpager.widget.ViewPager
    android:id="@+id/pager"
    android:overScrollMode="never"
    android:layout_marginStart="16dp"
    android:layout_marginTop="20dp"
    android:layout_marginEnd="16dp"
    android:layout_marginBottom="10dp"
    android:layout_height="match_parent"
    android:layout_width="match_parent">
</RelativeLayout>

采用这种布局的片段:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
    val view =  inflater.inflate(layoutId(), container, false)
    view.findViewById<ViewPager>(R.id.pager).adapter = TextPagerAdapter(activity!!.supportFragmentManager, listOf())
    return  view
}

TextPagerAdapter:

override fun getItem(position: Int): Fragment = PageFragment.newInstance("sssssss ssss $position")

    override fun getCount() = 5//pageText.size
}

页面片段:

override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
    val view = inflater.inflate(layoutId(), container, false)
    view.findViewById<TextView>(R.id.page_content_textView).text = arguments!!.getCharSequence(PAGE_TEXT)
    return view
}

我忘了检查内容片段是否已经创建。 解决方案是检查 savedInstanceState == null。如果该条件为真,则创建新片段。

在我的活动中:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    if(savedInstanceState == null) this.supportFragmentManager.beginTransaction()
    .add(containerViewId, CollectionDemoFragment()).commit()
}