RecyclerView added the SnapHelper class in version 24.2.0 to help RecyclerView align items at the end of scrolling.

SnapHelper is an abstract class that uses a subclass called LinearSnapHelper to keep the RecyclerView items in the middle of the class when scrolling stops. Version 25.1.0 official also provides a PagerSnapHelper subclass, can make RecyclerView like ViewPager effect, can only slide one page at a time, and center display.

Example:

Write the Activity layout: 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>
Copy the code

Write the item layout: 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="Click the button to jump" />

</LinearLayout>
Copy the code

Initialize 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 {
                return50 } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { } inner class Holder(itemView: View) : Recyclerview. ViewHolder(itemView) {init {}}} //LinearSnapHelper: Make the current Item center showed that can slide inertia val snapHelper = LinearSnapHelper () snapHelper. AttachToRecyclerView (recycler)}Copy the code

Display effect:

Using PagerSnapHelper

//PagerSnapHelper: a viewpager-like effect that slides one page at a time. val snapHelper2 = PagerSnapHelper() snapHelper2.attachToRecyclerView(recycler)Copy the code

Display effect: