Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

การทำงานกับ RecyclerView ในแอป Android ด้วย Kotlin

ภาพรวม

ตัวอย่างนี้สาธิตการใช้ RecyclerView พร้อม CardView และ ViewHolder Pattern สำหรับแสดงรายการข้อมูลอย่างมีประสิทธิภาพ (แทน ListView เดิม)

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio เลือก File → New Project

ขั้นตอนที่ 2: เพิ่ม Dependency (build.gradle)

dependencies {
    implementation "androidx.recyclerview:recyclerview:1.3.2"
    implementation "androidx.cardview:cardview:1.0.0"
}

ขั้นตอนที่ 3: Layout หลัก (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

ขั้นตอนที่ 4: MainActivity.kt

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {
    private val movieList = mutableListOf<MovieModel>()
    private lateinit var moviesAdapter: MoviesAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        moviesAdapter = MoviesAdapter(movieList)

        val layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = layoutManager
        recyclerView.itemAnimator = DefaultItemAnimator()
        recyclerView.adapter = moviesAdapter

        // เพิ่ม Divider (Optional)
        // recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))

        prepareMovieData()
    }

    private fun prepareMovieData() {
        val movies = listOf(
            MovieModel("Mad Max: Fury Road", "Action & Adventure", "2015"),
            MovieModel("Inside Out", "Animation, Kids & Family", "2015"),
            MovieModel("Star Wars: Episode VII - The Force Awakens", "Action", "2015"),
            MovieModel("Shaun the Sheep", "Animation", "2015"),
            MovieModel("The Martian", "Science Fiction & Fantasy", "2015"),
            MovieModel("Mission: Impossible Rogue Nation", "Action", "2015"),
            MovieModel("Up", "Animation", "2009"),
            MovieModel("Star Trek", "Science Fiction", "2009"),
            MovieModel("The LEGO Movie", "Animation", "2014"),
            MovieModel("Iron Man", "Action & Adventure", "2008"),
            MovieModel("Aliens", "Science Fiction", "1986"),
            MovieModel("Chicken Run", "Animation", "2000"),
            MovieModel("Back to the Future", "Science Fiction", "1985"),
            MovieModel("Raiders of the Lost Ark", "Action & Adventure", "1981"),
            MovieModel("Goldfinger", "Action & Adventure", "1965"),
            MovieModel("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014")
        )
        movieList.addAll(movies)
        moviesAdapter.notifyDataSetChanged()
    }
}

ขั้นตอนที่ 5: Data Model (MovieModel.kt)

data class MovieModel(
    val title: String,
    val genre: String,
    val year: String
)

ขั้นตอนที่ 6: Adapter (MoviesAdapter.kt)

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.NonNull
import androidx.recyclerview.widget.RecyclerView

class MoviesAdapter(private val moviesList: List<MovieModel>) :
    RecyclerView.Adapter<MoviesAdapter.MyViewHolder>() {

    inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val title: TextView = view.findViewById(R.id.title)
        val year: TextView = view.findViewById(R.id.year)
        val genre: TextView = view.findViewById(R.id.genre)
    }

    @NonNull
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val itemView = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_movie, parent, false)
        return MyViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val movie = moviesList[position]
        holder.title.text = movie.title
        holder.genre.text = movie.genre
        holder.year.text = movie.year
    }

    override fun getItemCount(): Int = moviesList.size
}

ขั้นตอนที่ 7: Item Layout (item_movie.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    app:cardBackgroundColor="@android:color/white"
    app:cardCornerRadius="8dp"
    app:cardElevation="4dp"
    app:cardUseCompatPadding="true">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp">

        <TextView
            android:id="@+id/title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:textColor="@android:color/black"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/year" />

        <TextView
            android:id="@+id/year"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/darker_gray"
            android:textSize="14sp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

        <TextView
            android:id="@+id/genre"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:textColor="@android:color/black"
            android:textSize="14sp"
            app:layout_constraintTop_toBottomOf="@id/title"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>

ขั้นตอนที่ 8: Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.recyclerviewdemo">
    <application ... >
        <activity android:name=".MainActivity"> ... </activity>
    </application>
</manifest>

ฟีเจอร์เพิ่มเติมที่น่าสนใจ

1. Click Listener

// ใน Adapter
inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    init {
        itemView.setOnClickListener {
            val position = adapterPosition
            if (position != RecyclerView.NO_POSITION) {
                listener?.onItemClick(moviesList[position])
            }
        }
    }
}

var listener: OnItemClickListener? = null
interface OnItemClickListener {
    fun onItemClick(movie: MovieModel)
}

// ใน Activity
moviesAdapter.listener = object : MoviesAdapter.OnItemClickListener {
    override fun onItemClick(movie: MovieModel) {
        Toast.makeText(this@MainActivity, "Clicked: ${movie.title}", Toast.LENGTH_SHORT).show()
    }
}

2. DiffUtil (Performance Optimization)

class MoviesAdapter : ListAdapter<MovieModel, MyViewHolder>(DiffCallback()) {
    // ใช้ ListAdapter แทน RecyclerView.Adapter
    // notifyDataSetChanged() ไม่ต้องเรียก ใช้ submitList() แทน
}

class DiffCallback : DiffUtil.ItemCallback<MovieModel>() {
    override fun areItemsTheSame(oldItem: MovieModel, newItem: MovieModel) = oldItem.title == newItem.title
    override fun areContentsTheSame(oldItem: MovieModel, newItem: MovieModel) = oldItem == newItem
}

3. Grid/Staggered Layout

// Grid
recyclerView.layoutManager = GridLayoutManager(this, 2)

// Staggered (Pinterest style)
recyclerView.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)

การทดสอบ

รันแอป จะแสดงรายการภาพยนตร์ 16 เรื่องในรูปแบบ CardView เลื่อนได้ลื่นไหล