我想保留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
}
}
我该如何实现?
答案 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)
希望这会有所帮助。谢谢