Select RecyclerView Adapter 中一次只有一个 ImageView

Select just one ImageView at a time inside RecyclerView Adapter

我有一个充满不同图像的 RecyclerView,当用户单击其中一个时,我会应用边框来突出显示图像。一切正常,但是,用户可以单击多个图像,然后所有图像都突出显示,我想 select 一次只显示一个。我搜索了多个网站和帖子,但其中 none 个有适合我的解决方案。这是一张图片:

我使用的是 ImageView 点击监听器,而不是 ItemClickListener。

适配器代码如下:

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView

class AccountViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    var accountImage: ImageView = 
        view.findViewById(R.id.account_image_placeholder)
}

class AddEditAccountAdapter(private var context: Context, private var 
    accountImages: ArrayList<String>) :
    RecyclerView.Adapter<AccountViewHolder>() {

       override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): 
AccountViewHolder {
    val imageItem = LayoutInflater.from(context).inflate(
        R.layout.account_image_item,
        parent, false
    )

    return AccountViewHolder(imageItem)
}

override fun getItemCount(): Int {
    return accountImages.size
}

override fun onBindViewHolder(holder: AccountViewHolder, position: Int) {

    val accountImageId =
        context.getResources().getIdentifier(accountImages.get(position), "drawable", context.getPackageName())

    holder.accountImage.setImageResource(accountImageId)

    holder.accountImage.setOnClickListener {

        holder.accountImage.setBackgroundResource(R.drawable.image_highlight)
    }
}
}

你应该有一个全局字段来保持你的 selected 位置,如下所示:

var selectedPos = -1 // hold selected position in your adapter
// in your bindView, because your view will be reused, you should always check the selected position to set the suitable background
holder.accountImage.setBackgroundResource(if(selectedPos == position) yourImageHightlight else yourNormalImage)

holder.accountImage.setOnClickListener {
    selectedPos = position
    notifyDataSetChanged()// or something like notifyItemChanged()...
}