Displaying Items in A List Using RecyclerView
Displaying Items in A List Using RecyclerView
This example will display a list of contacts with their names and phone numbers. We will include custom layouts
for each item in the list, and a click listener for each item.
Create an XML layout file for individual items in the RecyclerView. This layout will contain a TextView
for the contact name and another TextView for the phone number.
<TextView
android:id="@+id/contactName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="@android:color/black"/>
<TextView
android:id="@+id/contactPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="@android:color/darker_gray"/>
</LinearLayout>
Create an adapter that will bind the contact data to the RecyclerView items.
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class ContactAdapter(
private val contactList: List<Contact>,
private val itemClickListener: OnItemClickListener
) : RecyclerView.Adapter<ContactAdapter.ContactViewHolder>() {
interface OnItemClickListener {
fun onItemClick(contact: Contact)
}
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Set up the RecyclerView in your activity, initialize the adapter, and handle item clicks.
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
Explanation: