Reputation:
I have a simple RecyclerView, I want to make it behave like PlayStore recycler view on horizontal scrolling. By PlayStore behaviour, I mean when ever scrolled to a position it either rewinds back to the same element or change to another position. The Screen Cast have it clearly.
Here is a full width implementation
And another one, a relatively small width implementation. both from PlayStore.
My simple Recycler is the common one.,
The layout
<?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>
Adapter
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
Upvotes: 0
Views: 398
Reputation: 211
Tool you are looking for is called SnapHelper.
Java way:
SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(yourRecyclerView);
Kotlin way:
val snapHelper = LinearSnapHelper()
snapHelper.attachToRecyclerView(yourRecyclerView)
After this it most likely should work as in app store.
Upvotes: 1