如何使 Recycler View 表现得像 PlayStore Recycler Views

How to make Recycler View to behave like PlayStore Recycler Views

我有一个简单的 RecyclerView,我想让它在水平滚动时表现得像 PlayStore 回收器视图。通过 PlayStore 的行为,我的意思是当滚动到一个位置时,它要么倒回到同一元素,要么改变到另一个位置。 Screen Cast 已经很清楚了。

这是一个全宽的实现

还有一个,宽度相对较小的实现。均来自 PlayStore。

我的简单回收器是普通的,

布局

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_margin="10dp"
    app:cardElevation="6dp">
  
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp">
  
        <ImageView
            android:id="@+id/imageview"
            android:layout_width="40dp"
            android:layout_height="40dp" />
  
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginLeft="15dp"
            android:text="Item"
            android:textSize="20sp"
            android:textStyle="bold" />
  
    </LinearLayout>
  
</androidx.cardview.widget.CardView>

适配器

class CustomAdapter(private val mList: List<ItemsViewModel>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.card_view_design, parent, false)

        return ViewHolder(view)
    }

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

    }

    override fun getItemCount(): Int {
        return mList.size
    }

    class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
        val imageView: ImageView = itemView.findViewById(R.id.imageview)
        val textView: TextView = itemView.findViewById(R.id.textView)
    }
}

activity

val recyclerview = findViewById<RecyclerView>(R.id.recyclerview)
recyclerview.layoutManager = LinearLayoutManager(this)
val data = ArrayList<ItemsViewModel>()
val adapter = CustomAdapter(data)
recyclerview.adapter = adapter

您正在寻找的工具叫做 SnapHelper。

Java方式:

SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(yourRecyclerView);

Kotlin 方式:

val snapHelper = LinearSnapHelper()
snapHelper.attachToRecyclerView(yourRecyclerView)

在此之后它很可能应该像在应用商店中一样工作。