Wednesday, October 13, 2021

How to RecyclerView smooth scroll - Kotlin Example

 MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        // initialize a mutable list of animals

        val animals = mutableListOf(

            "Horse", "Donkey", "Goat",

            "Squirrel", "Mouse", "Chameleon",

            "Deer", "Raccoon", "Antelope",

            "Beaver", "Weasel", "Hedgehog",

            "Ferret", "Koala", "Wolf",

            "Lynx", "Groundhog", "Anteater",

            "Wombat"

        )

        // initialize an instance of linear layout manager

        val layoutManager = LinearLayoutManager(

            this, // context

            RecyclerView.VERTICAL, // orientation

            false // reverse layout

        ).apply {

            // specify the layout manager for recycler view

            recyclerView.layoutManager = this

        }

        // finally, data bind the recycler view with adapter

        val adapter = RecyclerViewAdapter(animals).apply {

            recyclerView.adapter = this

        }

        // smooth scroll to recycler view item position

        // smooth scroll to recycler view top

        btnTop.setOnClickListener {

            recyclerView.smoothScrollToPosition(0)

        }

        // smooth scroll to recycler view middle item

        btnMiddle.setOnClickListener {

            recyclerView.smoothScrollToPosition(adapter.itemCount/2)

        }

        // smooth scroll to recycler view bottom

        btnBottom.setOnClickListener {

            recyclerView.smoothScrollToPosition(adapter.itemCount-1)

        }

    }

}

RecyclerViewAdapter.kt

class RecyclerViewAdapter(private val animals: MutableList<String>)

    : RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        // inflate the custom view from xml layout file

        val view: View = LayoutInflater.from(parent.context)

            .inflate(R.layout.custom_view,parent,false)


        // return the view holder

        return ViewHolder(view)

    }

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

        // display the current animal

        holder.animal.text = "${position+1}. ${animals[position]}"

    }

    override fun getItemCount(): Int {

        // number of items in the data set held by the adapter

        return animals.size

    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){

        val animal: TextView = itemView.tvAnimal

    }

    // this two methods useful for avoiding duplicate item

    override fun getItemId(position: Int): Long {

        return position.toLong()

    }

    override fun getItemViewType(position: Int): Int {

        return position

    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/constraintLayout"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity"

    android:background="#F5FFFA">

    <androidx.recyclerview.widget.RecyclerView

        android:id="@+id/recyclerView"

        android:layout_width="0dp"

        android:layout_height="0dp"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintEnd_toEndOf="parent"

        app:layout_constraintHorizontal_bias="1.0"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toBottomOf="@+id/btnTop" />

    <Button

        android:id="@+id/btnTop"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginStart="8dp"

        android:layout_marginTop="8dp"

        android:text="Top"

        android:backgroundTint="#23297A"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toTopOf="parent" />

    <Button

        android:id="@+id/btnMiddle"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginStart="8dp"

        android:backgroundTint="#23297A"

        android:text="Middle"

        app:layout_constraintBottom_toBottomOf="@+id/btnTop"

        app:layout_constraintStart_toEndOf="@+id/btnTop" />

    <Button

        android:id="@+id/btnBottom"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginStart="8dp"

        android:backgroundTint="#23297A"

        android:text="Bottom"

        app:layout_constraintBottom_toBottomOf="@+id/btnMiddle"

        app:layout_constraintStart_toEndOf="@+id/btnMiddle" />

</androidx.constraintlayout.widget.ConstraintLayout>

custom_view.xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.cardview.widget.CardView

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:id="@+id/cardView"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    app:cardBackgroundColor="#FF6E4A"

    app:cardCornerRadius="8dp"

    app:cardElevation="3dp"

    app:cardMaxElevation="6dp"

    app:contentPadding="24dp"

    android:layout_margin="4dp">

    <androidx.constraintlayout.widget.ConstraintLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content">

        <TextView

            android:id="@+id/tvAnimal"

            android:layout_width="0dp"

            android:layout_height="wrap_content"

            android:fontFamily="sans-serif-condensed-medium"

            android:textColor="#F8D568"

            android:textSize="25sp"

            app:layout_constraintEnd_toEndOf="parent"

            app:layout_constraintStart_toStartOf="parent"

            app:layout_constraintTop_toTopOf="parent"

            tools:text="Text View" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>

build.gradle(app) [code to add]

dependencies {

    // card view

    implementation "androidx.cardview:cardview:1.0.0"


    // recycler view

    implementation "androidx.recyclerview:recyclerview:1.1.0"

}

How to RecyclerView smooth scroll

2 comments:


  1. Thanks for this information. it is helpfull and worthy
    Laptop Repair Center offers quality service for your laptop at a reasonable cost. We offer doorstep support, 24*7 onsite support, repair all brand laptops, have an expert team for onsite support, and much more. for more contact us on 7291903784
    laptop repair center in Delhi

    ReplyDelete
  2. i found it very helpful. thank u

    Mast Banarasi Paan is one of the best selling paan such as Rajwadi paan, Laddu paan, Choclate Paan, Fire paan, Silver paan. Mast Banarasi Paan is made available to every customer with unique flavor, quality taste, and hygiene and we are the best paan provider in India.
    banarasi paan

    ReplyDelete