我有一个构造RecyclerView的适配器类。我希望这个RecyclerView有一个按钮,更新RecyclerView外部的ImageView。这段代码更新了RecyclerView内部的图像,但我无法让它更新外部的图像。
class CustomAdapter(private val mList: List<ItemsViewModel>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
// create new views
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
// inflates the card_view_design view
// that is used to hold list item
val mainXML = LayoutInflater.from(parent.context)
.inflate(R.layout.activity_main, parent, false)
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.card_view_design, parent, false)
return ViewHolder(view, mainXML)
}
// binds the list items to a view
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val ItemsViewModel = mList[position]
// sets the image to the imageview from our itemHolder class
Picasso.get().load("https://img.pokemondb.net/sprites/x-y/normal/" + ItemsViewModel.text + ".png").into(holder.imageView)
// sets the text to the textview from our itemHolder class
holder.textView.text = ItemsViewModel.text
holder.buttonView.setOnClickListener {
Log.e("GIF selecter", holder.pokemonSelect.toString())
holder.pokemonSelect.setImageResource(R.drawable.ic_launcher_background)
Picasso.get().load("https://img.pokemondb.net/sprites/x-y/normal/golbat.png").into(holder.pokemonSelect) //This is the line of troubles, changing it to "holder.imageView" changes the image inside the recyclerview. I want it to change an image outside the recyclerview
}
}
// return the number of the items in the list
override fun getItemCount(): Int {
return mList.size
}
// Holds the views for adding it to image and text
class ViewHolder(ItemView: View, mainPage: View) : RecyclerView.ViewHolder(ItemView) {
val pokemonSelect: ImageView = mainPage.findViewById(R.id.pokemonSelect)
val imageView: ImageView = itemView.findViewById(R.id.pokemonImg)
val textView: TextView = itemView.findViewById(R.id.pokemon)
val buttonView: Button = itemView.findViewById(R.id.changeGIF)
}
}
1条答案
按热度按时间2jcobegt1#
问题是你在
createViewHolder
内部膨胀了activity_main.xml
,它什么也没做,因为它没有指向实际的activity_main
示例,而是创建了一个新的View
示例,它根本没有渲染/附加到层次结构。即使将inflate的第三个参数设置为true
,它仍然是回收器项的子项,而不是主布局,这是在adapter
的构造函数中传递所需外部ImageView
的理想方法。