Android RecyclerView实现ViewPager效果,用LinearSnapHelper

转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/128801968
本文出自【赵彦军的博客】

文章目录

LinearSnapHelper效果

所有代码都上传至 github

https://github.com/zyj1609wz/SnapHelperApp

SnapHelper是RecyclerView功能的一种拓展,使RecyclerView滑动行为类似ViewPager,无论怎么滑动最终停留在某页正中间。ViewPager一次只能滑动一页,RecyclerView+SnapHelper方式可以一次滑动好几页,且最终都停留在某页正中间。非常实用和酷炫。

SnapHelper的实现原理是监听RecyclerView.OnFlingListener中的onFling接口。LinearSnapHelper是抽象类SnapHelper的具体实现

在这里插入图片描述

上面的效果只需下面几行代码即可

val snapHelper = LinearSnapHelper()
//保证recyclerView滚动停止是,可以停在中间位置,类似于viewPager效果
       snapHelper.attachToRecyclerView(binding.recycler)

整体代码非常少,如下:

class MainActivity : AppCompatActivity() {
    
    

    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        binding.recycler.layoutManager = layoutManager
        binding.recycler.adapter = MyAdapter(listOf("1", "2", "3", "4", "5", "6", "7", "8"))

        val snapHelper = LinearSnapHelper()
        //保证recyclerView滚动停止是,可以停在中间位置,类似于viewPager效果
        snapHelper.attachToRecyclerView(binding.recycler)

        binding.btn.setOnClickListener {
    
    
            //获取中间位置的position
            val view = snapHelper.findSnapView(layoutManager)
            if (view != null) {
    
    
                val position = layoutManager.getPosition(view)
                Toast.makeText(this, " $position", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/zhaoyanjun6/article/details/128801968