繁体   English   中英

我怎样才能在 Kotlin 中做到这一点?

[英]How can I do this in Kotlin?

我需要 Kotlin 应用程序的帮助

在我编写的 Java 程序中,我可以这样做:

public class GameAdapter extends RecyclerView.Adapter<GameViewHolder> {
private final List<Card> cards;
private final Context context;
private final View.OnClickListener cardOnClickListener;

public GameAdapter(List<Card> cards, Context context, View.OnClickListener cardOnClickListener) {
    this.cards = cards;
    this.context = context;
    this.cardOnClickListener = cardOnClickListener;
}

然后像这样实例化适配器:

gameAdapter = new GameAdapter(dataSet, this, this::manageCardClick);

所以每次点击列表都会带我去 manageCardClick() 函数

但在 Kotlin 我这样做

class FeaturedProductsAdapter(list: List<Product>, listener: View.OnClickListener): RecyclerView.Adapter<FeaturedProductsViewHolder>() {

private var featuredProductsList: List<Product> = list
private var clickListener: View.OnClickListener = listener

然后

featuredAdapter = FeaturedProductsAdapter(featuredProductsDataSet, ::onProductClick)

但这给了我类型不匹配。 必需:(查看!)→ 找到的单元:KFunction1<产品,单元>

我怎样才能在 Kotlin 中做我在 Java 中所做的事情? 提前致谢。

我解决了,忘了反射函数(::onProductClick)要带一个View类型参数,然后拿到我在ViewHolder中绑定的tag来拿到Product

如果有人想知道:

class FeaturedProductsViewHolder(itemView: View, private val clickListener: View.OnClickListener) : RecyclerView.ViewHolder(itemView) {

    fun bind(product: Product) {
        itemView.apply {
            Picasso.get().load(product.imageUrl).into(this.findViewById<AppCompatImageView>(R.id.home_featured_products_cell_image))
            this.findViewById<AppCompatTextView>(R.id.home_featured_products_price).text = product.price.toString()
            this.findViewById<AppCompatTextView>(R.id.home_featured_products_product_name).text = product.name
            this.setOnClickListener(clickListener)
            this.tag = product
        }
    }

}

然后

featuredAdapter = FeaturedProductsAdapter(featuredProductsDataSet, ::onProductClick)

最后

private fun onProductClick(view: View) {
    val clickedProduct = view.tag
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM