在RecyclerView适配器中一次仅选择一个ImageView

时间:2019-01-30 15:58:42

标签: android kotlin android-imageview selected

我有一个装有不同图像的RecyclerView,当用户单击其中一个时,我会应用边框以突出显示图像。一切工作正常,但是,用户可以单击多个图像,然后全部突出显示,我一次只能选择一个。我已经搜索了多个站点和帖子,但是它们都没有适合我的解决方案。这是一张图片:

Image selected

我正在使用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)
    }
}
}

1 个答案:

答案 0 :(得分:1)

您应该拥有一个全局字段来保持您的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()...
}