简体   繁体   中英

How can I do this in Kotlin?

I need help for a Kotlin app

In a Java program I wrote, I can do this:

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;
}

And then instantiate the adapter like this:

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

So each click on the list takes me to manageCardClick() function

But in Kotlin I do this

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

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

And then

featuredAdapter = FeaturedProductsAdapter(featuredProductsDataSet, ::onProductClick)

But this gives me Type mismatch. Required: (View!) → Unit Found: KFunction1<Product, Unit>

How can I do what I did in Java in Kotlin? Thanks in advance.

I solved it, I forgot that the reflected function (::onProductClick) has to take a View type parameter, and then get the tag I binded in the ViewHolder to get the Product

If anyone wants to know:

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
        }
    }

}

Then

featuredAdapter = FeaturedProductsAdapter(featuredProductsDataSet, ::onProductClick)

And finally

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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