![](/img/trans.png)
[英]ViewPager with fragments: crash after orientation change (incorrect fragment displayed)
[英]Two pieces of fragments are displayed on orientation change to landscape with ViewPager2
我正在使用带有ViewPager2
的WebView
,在纵向模式下它向我显示单页,但是当我切换到横向模式时,它显示当前页面的一半和上一页的一半。
我在清单中有android:configChanges="orientation|screenSize"
以避免破坏和重新创建查看器。
适配器
class ViewPageAdapter(
private val tabs: ArrayList<Tab>, childFragmentManager: FragmentManager, lifecycle: Lifecycle
): FragmentStateAdapter(childFragmentManager, lifecycle) {
override fun getItemCount(): Int = tabs.size
override fun createFragment(position: Int): Fragment {
return tabs[position].fragment
}
override fun containsItem(itemId: Long): Boolean {
return tabs.map { it.tabId }.contains(itemId)
}
override fun getItemId(position: Int): Long {
return tabs[position].tabId
}
fun removeItem(index: Int) {
tabs.removeAt(index)
notifyItemRemoved(index)
notifyItemRangeChanged(index, tabs.size)
notifyDataSetChanged()
}
}
设置浏览器
adapter = ViewPageAdapter(browser.tabs, childFragmentManager, lifecycle)
binding.viewPager.adapter = adapter
binding.viewPager.offscreenPageLimit = 100
binding.viewPager.isUserInputEnabled = false
这似乎是ViewPager2
中的一个错误。 https://issuetracker.google.com/issues/175796502?pli=1
我使用以下解决方法暂时解决了这个问题。 当我有上一页时出现问题,所以我所做的就是切换到上一页并切换回当前页面而没有平滑滚动,我希望他们能尽快修复这个错误。
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE || newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
val c = currentPageIndex
binding.viewPager.setCurrentItem(if (currentPageIndex-1 > 0) currentPageIndex-1 else 0, false)
binding.viewPager.setCurrentItem(c, false)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.