如何在recyclerView 的图片上添加onClickListener?

How to add onClickListener on images in recyclerView?

我正在尝试使用 Glide 框架在这段代码中的图像上附加 onclick 侦听器,但我找不到解决方案。有人可以帮忙吗?

图像已经显示在模拟器中。

提前致谢

package com.example.andoridlifecycle.adapters

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.andoridlifecycle.R
import kotlinx.android.synthetic.main.item_custom_row.view.*

class ItemAdapter(private val context: Context, private val urls: ArrayList<String>) :
    RecyclerView.Adapter<ItemAdapter.ViewHolder>() {


    /**
     * Inflates the custom view which is designed in xml layout file
     */
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(context).inflate(
                R.layout.item_custom_row,
                parent,
                false
            )
        )
    }


    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        // Array with urls
        val url = urls[position]

        Glide.with(context)
            .load(url)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .placeholder(R.drawable.placeholder)
            .into(holder.imageView)
    }

    // Gets the number of items in the list
    override fun getItemCount(): Int {
        return urls.size
    }
     // A ViewHolder describes an item view and metadata about its place within the RecyclerView.

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {

        val imageView: ImageView = view.iv_image
     }
}

我是 Java 开发人员,所以我无法使用 Kotlin 进行编码,但我将向您展示如何在 imageView 上设置 OnClickListener。在 imageView 上使用 OnclickListener 不需要 Glide 库。 只需在您的 onBindViewHolder

中添加以下几行
holder.imageView.setOnClickListener(view -> {
            Toast.makeText(context, "this is number: "+position+" Image Selected", Toast.LENGTH_SHORT).show();
            // or your code for imageView
        });

您的新代码如下所示:-

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        // Array with urls
        val url = urls[position]

//code for onClick on image
holder.imageView.setOnClickListener(view -> {
            Toast.makeText(context, "this is number: "+position+" Image Selected", Toast.LENGTH_SHORT).show();
            // or your code for imageView
        });


        Glide.with(context)
            .load(url)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .placeholder(R.drawable.placeholder)
            .into(holder.imageView)
    }

确保将我的代码中的 JAVA 更改为 Kotlin。如果您有任何问题,请告诉我