如何计算 ViewPager2 中发生的滑动
Posted
技术标签:
【中文标题】如何计算 ViewPager2 中发生的滑动【英文标题】:How to tally the swipes that occur in ViewPager2 【发布时间】:2021-10-12 04:10:05 【问题描述】:所以我创建了一个带有图片的轮播类型应用程序。我想记录用户的滑动次数并将其显示在计数器上。
*计数器在“滑动次数”旁边
这是我目前在代码中得到的内容
class MainFragment: Fragment()
// private lateinit var manager: RecyclerView.LayoutManager
private lateinit var viewPager: ViewPager2
private var counter: Int = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View?
val binding: MainFragmentBinding = DataBindingUtil.inflate(
inflater,
R.layout.main_fragment,
container, false)
viewPager = binding.imageSlider
val data: MutableList<CarouselItem> = ArrayList()
data.add(CarouselItem(1, bcw_65, "First"))
data.add(CarouselItem(2, bcw_66, "Second"))
data.add(CarouselItem(3, bcw_67, "Third"))
data.add(CarouselItem(4, bcw_68, "Fourth"))
data.add(CarouselItem(5, bcw_69, "Fifth"))
data.add(CarouselItem(6, bcw_70, "Sixth"))
data.add(CarouselItem(2, bcw_71, "Seventh"))
viewPager.adapter = CarouselItemAdapter(data, viewPager)
viewPager.clipToPadding = false
viewPager.clipChildren = false
viewPager.offscreenPageLimit = 3
viewPager.getChildAt(0).overScrollMode = RecyclerView.OVER_SCROLL_NEVER
val compositePageTransformer = CompositePageTransformer()
compositePageTransformer.addTransformer(MarginPageTransformer(30))
compositePageTransformer.addTransformer page, position ->
val r = 1 - abs(position)
page.scaleY = 0.85f + r * 0.25f
viewPager.setPageTransformer(compositePageTransformer)
// binding.imageSlider.setOnTouchListener
binding.imageSlider.setOnTouchListener v, event ->
counter++
Log.d(TAG, "onCreateView: Swipe Recorded")
true
binding.counterView.text = counter.toString()
return binding.root
我已经尝试了一些东西,但它似乎仍然没有真正起作用。任何想法将不胜感激。
【问题讨论】:
这能回答你的问题吗? How to detect the swipe left or Right in android? “我已经尝试了一些事情” - 你尝试了哪些事情? OnPageChangedListener 是您尝试过的一件事吗? developer.android.com/reference/androidx/viewpager/widget/… 我还没有尝试过 OnPageChangedListener。你介意详细说明一下吗? 【参考方案1】:将ViewPager2.OnPageChangeCallback
添加到您的寻呼机:
class MainFragment: Fragment()
private lateinit var viewPager: ViewPager2
private var counter: Int = 0
private var pageChangeCallback: ViewPager2.OnPageChangeCallback? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View?
...
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback()
override fun onPageSelected(position: Int)
counter++
binding.counterView.text = counter.toString()
.also pageChangeCallback = it )
...
override fun onDestroyView()
super.onDestroyView()
viewPager.unregisterOnPageChangeCallback(pageChangeCallback!!)
pageChangeCallback = null
【讨论】:
你是绝对正确的。我不完全确定如何实际实现 OnPageChangeCallback。我很感激。以上是关于如何计算 ViewPager2 中发生的滑动的主要内容,如果未能解决你的问题,请参考以下文章
ViewPager2嵌套RecyclerView滑动冲突解决办法