我尝试仅在一个方向(向右)上启用ViewPager2中的滑动。我有5页。
我在活动中尝试了此操作
viewPager2.registerOnPageChangeCallback(object :
ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
if (currentPage == position) {
dataBinding.viewPager2.setUserInputEnabled(false)
}
if (currentPage < position) { // swipe left
dataBinding.viewPager2.setUserInputEnabled(true)
} else if (currentPage > position) { // swipe right
dataBinding.viewPager2.setUserInputEnabled(false)
}
currentPage = position;
}
})
但没有帮助。禁用两个方向。
答案 0 :(得分:0)
尝试这种方式
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager2.widget.ViewPager2
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
var previousPage: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewpager.adapter = MyAdapter(this)
viewpager.orientation = ViewPager2.ORIENTATION_HORIZONTAL
// try this to disable swiping in previous page
viewpager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
if (position < previousPage) {
viewpager.setCurrentItem(previousPage, true)
} else {
previousPage = position
}
}
})
}
}