Bird
Raised Fist0
Android Kotlinmobile~20 mins

Item keys for performance in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Simple Item List
This screen shows a scrollable list of items with unique keys to improve performance during updates.
Target UI
-------------------------
| Simple Item List       |
|-----------------------|
| • Item 1              |
| • Item 2              |
| • Item 3              |
| • Item 4              |
| • Item 5              |
|                       |
-------------------------
Display a vertical list of 5 items labeled 'Item 1' to 'Item 5'.
Use RecyclerView with an Adapter that assigns a unique stable ID (key) to each item.
Enable stable IDs in the adapter to optimize RecyclerView performance.
Ensure smooth scrolling and proper item recycling.
Starter Code
Android Kotlin
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

        // TODO: Enable stable IDs and implement getItemId() in adapter
    }
}

class ItemAdapter(private val items: List<String>) : RecyclerView.Adapter<ItemAdapter.ViewHolder>() {

    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

    // TODO: Override getItemId() and enable stable IDs
}
Task 1
Task 2
Solution
Android Kotlin
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.

Final Result
Completed Screen
-------------------------
| Simple Item List       |
|-----------------------|
| • Item 1              |
| • Item 2              |
| • Item 3              |
| • Item 4              |
| • Item 5              |
|                       |
-------------------------
User can scroll the list smoothly up and down.
RecyclerView reuses item views efficiently without flicker.
Performance is improved because each item has a stable unique key.
Stretch Goal
Add a button to shuffle the list items and update the RecyclerView while preserving smooth animations.
💡 Hint
Use notifyItemMoved() or DiffUtil with stable IDs to animate changes smoothly.

Practice

(1/5)
1. Why should you use unique keys for list items in Android Kotlin RecyclerView adapters?
easy
A. To make the list items look colorful
B. To help the system identify items for efficient updates and animations
C. To increase the size of the list
D. To slow down the app for testing

Solution

  1. Step 1: Understand the role of keys in lists

    Keys uniquely identify each item so the system can track changes efficiently.
  2. Step 2: Connect keys to performance benefits

    Using unique keys helps RecyclerView animate changes smoothly and update only changed items.
  3. Final Answer:

    To help the system identify items for efficient updates and animations -> Option B
  4. Quick Check:

    Unique keys improve performance [OK]
Hint: Keys uniquely identify items for smooth updates [OK]
Common Mistakes:
  • Using item position as key
  • Not using keys at all
  • Using non-unique keys
2. Which of the following is the correct way to provide a stable key in a RecyclerView adapter in Kotlin?
easy
A. override fun getItemId(position: Int) = position.toLong()
B. override fun getItemId(position: Int) = 0L
C. override fun getItemId(position: Int) = items[position].id
D. override fun getItemId(position: Int) = items.size.toLong()

Solution

  1. Step 1: Identify stable unique ID source

    Using a unique ID from the item data ensures stable keys.
  2. Step 2: Compare options

    override fun getItemId(position: Int) = items[position].id uses the item's unique id, while others use position or constants which are unstable or incorrect.
  3. Final Answer:

    override fun getItemId(position: Int) = items[position].id -> Option C
  4. Quick Check:

    Use unique item IDs for stable keys [OK]
Hint: Use unique item IDs, not positions, for keys [OK]
Common Mistakes:
  • Using position as key which can change
  • Returning constant key for all items
  • Using list size as key
3. Given the following code snippet in a RecyclerView adapter, what will happen if keys are not unique?
override fun getItemId(position: Int) = position.toLong()
medium
A. RecyclerView will crash immediately
B. RecyclerView will duplicate items automatically
C. RecyclerView will ignore the keys and work fine
D. RecyclerView may incorrectly animate or update items causing glitches

Solution

  1. Step 1: Understand position as key problem

    Using position as key is unstable because item positions can change when list updates.
  2. Step 2: Effect on RecyclerView behavior

    RecyclerView may confuse items during animations or updates, causing visual glitches but not crashes.
  3. Final Answer:

    RecyclerView may incorrectly animate or update items causing glitches -> Option D
  4. Quick Check:

    Non-unique keys cause update glitches [OK]
Hint: Non-unique keys cause animation glitches [OK]
Common Mistakes:
  • Thinking RecyclerView crashes on key issues
  • Assuming keys don't affect animations
  • Believing keys duplicate items
4. You notice your RecyclerView animations are glitchy after adding new items. Which of these fixes the problem?
medium
A. Use unique stable IDs in getItemId() and call setHasStableIds(true)
B. Remove all keys and rely on default behavior
C. Use item position as key in getItemId()
D. Disable animations completely

Solution

  1. Step 1: Identify cause of glitches

    Glitches often happen when keys are unstable or missing.
  2. Step 2: Apply correct fix

    Providing unique stable IDs and enabling stable IDs fixes animation glitches.
  3. Final Answer:

    Use unique stable IDs in getItemId() and call setHasStableIds(true) -> Option A
  4. Quick Check:

    Stable IDs fix animation glitches [OK]
Hint: Enable stable IDs with unique keys [OK]
Common Mistakes:
  • Ignoring setHasStableIds(true)
  • Using positions as keys
  • Disabling animations instead of fixing keys
5. You have a list of users with possible duplicate names but unique IDs. Which key strategy ensures best RecyclerView performance and correct animations?
hard
A. Use user IDs as keys in getItemId() and enable stable IDs
B. Use user names as keys since they are visible
C. Use list position as key because it is simple
D. Use a random number as key for each item

Solution

  1. Step 1: Analyze uniqueness of keys

    User IDs are unique, names may duplicate, positions change, random numbers are unstable.
  2. Step 2: Choose best key strategy

    Using unique user IDs with stable IDs enabled ensures correct item tracking and smooth animations.
  3. Final Answer:

    Use user IDs as keys in getItemId() and enable stable IDs -> Option A
  4. Quick Check:

    Unique stable IDs ensure best performance [OK]
Hint: Always prefer unique stable IDs over visible or position keys [OK]
Common Mistakes:
  • Using visible but non-unique fields as keys
  • Using position which changes on updates
  • Using random keys causing instability
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard