在特定视图上滑动时禁用ViewPager滑动

时间:2019-06-12 06:58:30

标签: java android kotlin

我想保留ViewPager的滑动功能,但是我想仅在布局文件中滑动某个View时禁用它(我是自定义的Preference扩展):

activity.xml

<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</androidx.viewpager.widget.ViewPager>

activity.kt

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_home)
    viewpager.addOnPageChangeListener(this)
    // Initialise FragmentAdapter
    val fragmentAdapter = ScreenSlidePagerAdapter(supportFragmentManager)
    viewpager.adapter = fragmentAdapter
    viewpager.currentItem = 1
}


private inner class ScreenSlidePagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm){
    override fun getItem(position: Int): Fragment {
        return when(position){
            0 -> {
                SettingsFragment()
            }
            2 -> {
                UserFragment()
            }
            else -> {
                MainFragment()
            }
        }
    }
    // 3 Fragments
    override fun getCount(): Int {
        return 3
    }

}

我该如何实现?

1 个答案:

答案 0 :(得分:0)

您可以使用此代码实现目标。

class LockableViewPager : ViewPager {
    private var swipeable: Boolean = false

    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        this.swipeable = true
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        return if (this.swipeable) {
            super.onTouchEvent(event)
        } else false
    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        return if (this.swipeable) {
            super.onInterceptTouchEvent(event)
        } else false
    }

    fun setSwipeable(swipeable: Boolean) {
        this.swipeable = swipeable
    }
}

然后您只需致电

setSwipeable(false)

希望这会有所帮助。谢谢