android - 安卓。单击 RecyclerView 中的项目时加载 Intent
问题描述
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()
}
推荐阅读
- html - 为什么我的 html 到 WordPress 转换主题的菜单不显示?
- vb.net - DrawString 上的文本未居中 vb.net
- typescript - NestJS:管道未应用于绑定的主体参数
- typescript - 打字稿错误地将元组推断为数组
- javascript - 在同一浏览器和新标签中打开 Cookie 横幅“隐私声明”
- javascript - 比较时间和日期是否包括在内?
- android - 在 Android MVVM 中,我需要创建多少个存储库和网络客户端来服务不同的查询?
- javascript - 对按名称分组的数字属性求和
- java - 在春天使用 cglib 的嵌套代理
- java - Docker 容器中的 FTP 上传文件失败