import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
val items = listOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5")
val adapter = ItemAdapter(items)
recyclerView.adapter = adapter
}
}
class ItemAdapter(private val items: List<String>) : RecyclerView.Adapter<ItemAdapter.ViewHolder>() {
init {
setHasStableIds(true)
}
class ViewHolder(val view: android.widget.TextView) : RecyclerView.ViewHolder(view)
override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): ViewHolder {
val textView = android.widget.TextView(parent.context)
textView.textSize = 20f
textView.setPadding(16, 16, 16, 16)
return ViewHolder(textView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.view.text = items[position]
}
override fun getItemCount(): Int = items.size
override fun getItemId(position: Int): Long {
return position.toLong()
}
}We enabled stable IDs by calling setHasStableIds(true) in the adapter's init block. This tells RecyclerView that each item has a unique ID that won't change.
Then, we override getItemId(position) to return a unique long value for each item. Here, we simply use the position as the unique ID.
This helps RecyclerView optimize item animations and recycling, improving performance especially when the list updates.