RecyclerView使用SnapHelper打造ViewPager

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)
    }

顯示效果:

使用PagerSnapHelper

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

顯示效果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章