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)
}
}
}
我的适配器
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)
}
}
}
当我单击RecyclerView中的项目时,什么也没有发生。
在onBindViewHolder
函数内部,替换为:
holder.itemView.setOnClickListener {
onClick(shoe)
}
有了这个:
holder.itemView.setOnClickListener {
onClick(shoe).invoke()
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句