我正试图使用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 Library。只需在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
。如果你有任何问题,请告诉我