如何让ViewPager2不那么敏感?

Igo*_*yuk 10 android kotlin android-viewpager2

我在我的应用程序中使用 ViewPager2,它有三个页面,每个页面显示不同的内容,问题是即使有人向下滚动并且错误地将手指向右移动一点,ViewPager 也会更改页面,这太明智了或离开。

那么我怎样才能让 ViewPager 不那么敏感呢?ViewPager2是在Activity中创建的

这是我初始化 ViewPager 的代码:

private lateinit var viewPager: ViewPager2
private lateinit var adapterView: ViewPagerAdapter

private fun initViewPager() {
    adapterView.addFragment(ElencoFragment())
    adapterView.addFragment(TestataFragment())
    adapterView.addFragment(CorpoFragment())
    adapterView.notifyDataSetChanged()

    viewPager.adapter = adapterView
    ...
}


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    viewPager = findViewById(R.id.pager)
    adapterView = ViewPagerAdapter(supportFragmentManager, lifecycle)
    ...
}
Run Code Online (Sandbox Code Playgroud)

我的适配器:

 class ViewPagerAdapter
        (manager: FragmentManager, lifecycle: Lifecycle) :
        FragmentStateAdapter(manager, lifecycle) {

        private var fragmentList: ArrayList<Fragment> = ArrayList()

        override fun getItemCount(): Int {
            return fragmentList.size
        }

        override fun createFragment(position: Int): Fragment {
            return fragmentList[position]
        }

        fun addFragment(fragment: Fragment) {
            fragmentList.add(fragment)
        }
    }
Run Code Online (Sandbox Code Playgroud)

Nav*_*edi 14

要降低 ViewPager 水平滚动的灵敏度,请尝试此扩展

fun ViewPager2.reduceDragSensitivity(f: Int = 4) {
    val recyclerViewField = ViewPager2::class.java.getDeclaredField("mRecyclerView")
    recyclerViewField.isAccessible = true
    val recyclerView = recyclerViewField.get(this) as RecyclerView

    val touchSlopField = RecyclerView::class.java.getDeclaredField("mTouchSlop")
    touchSlopField.isAccessible = true
    val touchSlop = touchSlopField.get(recyclerView) as Int
    touchSlopField.set(recyclerView, touchSlop*f)       // "8" was obtained experimentally
}
Run Code Online (Sandbox Code Playgroud)

来源

  • 我们怎样才能用java实现这个呢? (2认同)