class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.recyclerviewShoes.apply {
adapter = ShoeAdapter(ShoeRepository.getShoes())
{ shoeModel ->
val intent = Intent(this@MainActivity, ActivityProductDetail::class.java)
intent.putExtra(ActivityProductDetail.CATEGORY, shoeModel.product_name)
startActivity(intent)
}
layoutManager = LinearLayoutManager(this@MainActivity, LinearLayoutManager.HORIZONTAL, false)
}
}
}
My Adapter
class ShoeAdapter (
private val shoeList: List<ShoeModel>,
private val onClick: (ShoeModel) -> Unit
) : RecyclerView.Adapter<ShoeViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShoeViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = ItemProductBinding.inflate(layoutInflater, parent, false)
return ShoeViewHolder(binding)
}
override fun getItemCount() = shoeList.size
override fun onBindViewHolder(holder: ShoeViewHolder, position: Int) {
val shoe = shoeList[position]
holder.bind(shoe)
holder.itemView.setOnClickListener {
onClick(shoe)
}
}
}
class ShoeViewHolder(
private val binding: ItemProductBinding): RecyclerView.ViewHolder(binding.root) {
fun bind(shoe: ShoeModel) {
binding.apply {
textProductName.text = shoe.product_manufacturer
textShoeName.text = shoe.product_name
textPrice.text = shoe.product_price
imageShoe.setImageResource(shoe.image)
}
}
}
When I click the item in my RecyclerView, nothing happens.
Inside your onBindViewHolder
function, replace this:
holder.itemView.setOnClickListener {
onClick(shoe)
}
with this:
holder.itemView.setOnClickListener {
onClick(shoe).invoke()
}