एंड्रॉइड में RecyclerView का पूर्ण गाइड
RecyclerView एंड्रॉइड में सूची/ग्रिड प्रदर्शित करने के लिए सबसे लचीला और कुशल घटक है। यह ViewHolder पैटर्न और एडाप्टर का उपयोग करके बड़े डेटासेट को कुशलतापूर्वक संभालता है।
निर्भरताएं (build.gradle)
dependencies {
implementation "androidx.recyclerview:recyclerview:1.3.2"
implementation "androidx.cardview:cardview:1.0.0"
// सूची एनिमेशन के लिए वैकल्पिक
implementation "androidx.recyclerview:recyclerview-selection:1.2.1"
}
चरण 1: नया प्रोजेक्ट बनाएं
एंड्रॉइड स्टूडियो में File → New Project चुनें।
चरण 2: मुख्य लेआउट (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"
android:clipToPadding="false"
android:paddingBottom="16dp" />
</LinearLayout>
चरण 3: 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()
private lateinit var moviesAdapter: MoviesAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
moviesAdapter = MoviesAdapter(movieList) { movie ->
// क्लिक हैंडलिंग
showMovieDetails(movie)
}
// लेआउट मैनेजर (वर्टिकल सूची)
val layoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = layoutManager
// एनिमेशन
recyclerView.itemAnimator = DefaultItemAnimator()
// एडाप्टर सेट करें
recyclerView.adapter = moviesAdapter
// आइटम डेकोरेशन (वैकल्पिक - आइटम के बीच स्पेसिंग)
recyclerView.addItemDecoration(
DividerItemDecoration(this, layoutManager.orientation)
)
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()
}
private fun showMovieDetails(movie: MovieModel) {
// डायलॉग, नई एक्टिविटी, या टोस्ट दिखाएं
Toast.makeText(this, "${movie.title} (${movie.year})", Toast.LENGTH_SHORT).show()
}
}
चरण 4: MovieModel.kt (डेटा क्लास)
data class MovieModel(
val title: String,
val genre: String,
val year: String
) {
// वैकल्पिक: कॉपी के साथ अपडेट के लिए
fun withTitle(newTitle: String) = copy(title = newTitle)
fun withGenre(newGenre: String) = copy(genre = newGenre)
fun withYear(newYear: String) = copy(year = newYear)
}
चरण 5: MoviesAdapter.kt (आधुनिक ViewBinding के साथ)
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: MutableList,
private val onItemClick: (MovieModel) -> Unit
) : RecyclerView.Adapter() {
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)
init {
itemView.setOnClickListener {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
onItemClick(moviesList[position])
}
}
}
}
@NonNull
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.movie_list, 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
// डेटा अपडेट के लिए सहायक विधियाँ
fun addMovie(movie: MovieModel) {
moviesList.add(movie)
notifyItemInserted(moviesList.lastIndex)
}
fun removeMovie(position: Int) {
if (position in moviesList.indices) {
moviesList.removeAt(position)
notifyItemRemoved(position)
}
}
fun updateMovie(position: Int, movie: MovieModel) {
if (position in moviesList.indices) {
moviesList[position] = movie
notifyItemChanged(position)
}
}
fun setMovies(newMovies: List) {
moviesList.clear()
moviesList.addAll(newMovies)
notifyDataSetChanged()
}
}
चरण 6: आइटम लेआउट (movie_list.xml) - CardView के साथ
<?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:cardCornerRadius="12dp"
app:cardElevation="4dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/genre"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textColor="@android:color/darker_gray"
android:textSize="14sp" />
<TextView
android:id="@+id/year"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textColor="@android:color/darker_gray"
android:textSize="12sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
चरण 7: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.recyclerviewexample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
उन्नत RecyclerView सुविधाएं:
1. एकाधिक व्यू टाइप (हेडर, सामग्री, फुटर)
sealed class ListItem {
data class Header(val title: String) : ListItem()
data class Movie(val movie: MovieModel) : ListItem()
data class Footer(val text: String) : ListItem()
}
class MultiTypeAdapter(private val items: List) :
RecyclerView.Adapter() {
override fun getItemViewType(position: Int) = when (items[position]) {
is ListItem.Header -> 0
is ListItem.Movie -> 1
is ListItem.Footer -> 2
}
// ... onCreateViewHolder और onBindViewHolder को व्यू टाइप के अनुसार लागू करें
}
2. DiffUtil के साथ कुशल अपडेट (ListAdapter)
class MoviesAdapter : ListAdapter(MovieDiffCallback()) { class MovieDiffCallback : DiffUtil.ItemCallback () { override fun areItemsTheSame(oldItem: MovieModel, newItem: MovieModel): Boolean { return oldItem.title == newItem.title && oldItem.year == newItem.year } override fun areContentsTheSame(oldItem: MovieModel, newItem: MovieModel): Boolean { return oldItem == newItem } } // ... बाकी कार्यान्वयन } // उपयोग: adapter.submitList(newMovieList) // स्वचालित रूप से न्यूनतम अपडेट की गणना करता है
3. GridLayoutManager और StaggeredGridLayoutManager
// ग्रिड (2 कॉलम)
recyclerView.layoutManager = GridLayoutManager(this, 2)
// स्टैगर्ड ग्रिड (Pinterest-शैली)
recyclerView.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
// स्पैन आकार बदलें (हेडर के लिए पूर्ण चौड़ाई)
val gridLayoutManager = GridLayoutManager(this, 3)
gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return when (adapter.getItemViewType(position)) {
0 -> 3 // हेडर 3 कॉलम फैलाता है
else -> 1
}
}
}
recyclerView.layoutManager = gridLayoutManager
4. स्वाइप टू डिलीट और ड्रैग एंड ड्रॉप (ItemTouchHelper)
ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(
ItemTouchHelper.UP or ItemTouchHelper.DOWN, // ड्रैग दिशाएं
ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT // स्वाइप दिशाएं
) {
override fun onMove(recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder): Boolean {
val from = viewHolder.adapterPosition
val to = target.adapterPosition
// सूची में आइटम ले जाएं और एडाप्टर को सूचित करें
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
// आइटम हटाएं
adapter.removeMovie(position)
}
}).attachToRecyclerView(recyclerView)