Challenge 1: A Basic RecyclerView List — Solution
data class Product(val name: String, val price: Double)
// item_product.xml
//
//
//
//
class ProductAdapter(private val products: List) :
RecyclerView.Adapter() {
class ProductViewHolder(val binding: ItemProductBinding) :
RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
val binding = ItemProductBinding.inflate(
LayoutInflater.from(parent.context), parent, false
)
return ProductViewHolder(binding)
}
override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
val product = products[position]
holder.binding.nameText.text = product.name
holder.binding.priceText.text = "$${product.price}"
}
override fun getItemCount() = products.size
}
// MainActivity.kt — inside onCreate
val products = listOf(
Product("Keyboard", 49.99),
Product("Mouse", 19.99),
Product("Monitor", 179.99),
Product("Webcam", 39.99),
Product("Headset", 59.99)
)
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = ProductAdapter(products)
Notes:
- onCreateViewHolder only runs enough times to fill the visible screen
(plus a small buffer) — with 5 items on a typical phone screen, it
might run all 5 times, or fewer if not all items fit at once; scrolling
further wouldn't call it again for items already inflated once.
- onBindViewHolder runs once per item as it scrolls into view (and again
each time a recycled holder is reused for a different position), which
is why it should only set data on already-existing Views, never
inflate new ones.
- The RecyclerView itself needs a layoutManager assigned (LinearLayoutManager
here) before an adapter will actually render anything — a RecyclerView
with an adapter but no layoutManager shows nothing.