RecyclerView使用SnapHelper打造ViewPager

4,289 阅读1分钟

RecyclerView在24.2.0版本中新增了SnapHelper这个辅助类,用于辅助RecyclerView在滚动结束时将Item对齐到某个位置。

SnapHelper是一个抽象类,官方提供了一个LinearSnapHelper的子类,可以让RecyclerView滚动停止时相应的Item停留中间位置。25.1.0版本中官方又提供了一个PagerSnapHelper的子类,可以使RecyclerView像ViewPager一样的效果,一次只能滑一页,而且居中显示。

示例:

编写Activity布局:activity_snap

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</LinearLayout>

编写item布局:item_list

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="500dp"
    android:background="#00ff00"
    android:gravity="center"
    android:orientation="vertical"
    android:layout_margin="5dp">

    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="点击按钮跳转" />

</LinearLayout>

初始化RecyclerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_snap)

        recycler = findViewById(R.id.recycler)

        val manager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        recycler.layoutManager = manager
        recycler.adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
                val item = LayoutInflater.from(parent.context).inflate(R.layout.item_list, parent, false)
                item.setOnClickListener {
                    startActivity(Intent(parent.context, SwipeActivity::class.java))
                }
                return Holder(item)
            }

            override fun getItemCount(): Int {
                return 50
            }

            override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

            }

            inner class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
                init {

                }
            }

        }
        //LinearSnapHelper:使当前Item居中显示,可以惯性滑动
        val snapHelper = LinearSnapHelper()
        snapHelper.attachToRecyclerView(recycler)
    }

显示效果:

LinearSnapHelper

使用PagerSnapHelper

        //PagerSnapHelper:像ViewPager一样的效果,每次只能滑动一页。
        val snapHelper2 = PagerSnapHelper()
        snapHelper2.attachToRecyclerView(recycler)

显示效果:

PagerSnapHelper