Android Fragments 使用ViewPager2将方向更改为横向时显示两个片段

r7knjye2  于 5个月前  发布在  Android
关注(0)|答案(2)|浏览(79)

我使用的是WebView,里面有WebView,在纵向模式下,它显示的是一个页面,但是当我切换到横向模式时,它显示的是当前页面的一半和前一页面的一半。
我在清单中使用了android:configChanges="orientation|screenSize",以避免破坏和重新创建viewpager。

适配器

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


100d1x

的字符串

cig3rfwq

cig3rfwq1#

这似乎是一个bug在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)
    }
}

字符串

svujldwt

svujldwt2#

这是解决这个问题的Java代码

@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Check if the orientation has changed to landscape or portrait
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE || newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {

        // Save the current index for later use
        int currentIndex = index;

        // Set the ViewPager to the previous item, but not below the first item
        viewPager2.setCurrentItem(Math.max(index - 1, 0), false);

        // Reset the ViewPager to the original item to maintain user's current position
        viewPager2.setCurrentItem(currentIndex, false);
    }
}

字符串

相关问题