Home > Enterprise >  How can I access all imageviews from a position of an adapter of recyclerview in android?
How can I access all imageviews from a position of an adapter of recyclerview in android?

Time:03-09

In my program, there is a recyclerview. There is an imageview for an each item of the recyclerview. I need to change all item's imageview's image when a condition satisfies. so I need to access whole position's imageview from some position of the adapter. I need to access from inside of the adapter. I searched and found an answer from here. but that I only can access from our fragment/activity page. not from adapter. that code is

val row: View? = rvLocations?.layoutManager?.findViewByPosition(position)

How can I access the all views inside the adapter? Thank you

CodePudding user response:

it depend on how you build your adapter , here is complete adapter boilerplate using viewBinding in kotlin


class ItemListAdapter(
    private val list: List<ItemDataModel>,
    private val listener: OnItemClickListener
) : RecyclerView.Adapter<ItemListAdapter.ViewHolder>() {

    interface OnItemClickListener{
        fun onItemClick(view: View, position: Int)
    }

    inner class ViewHolder(private var binding: ItemListRcvBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: ItemDataModel, position: Int) {
            // you can get access to all your view and its position here
            // e.g:

            // context
            val context = binding.imageView1.context

            // clicklistener
            binding.imageView1.setOnclickListener{ view ->
               listener.onItemClick(view, position)
             }
         
            // change image by condition
            when(item.condision){
               conditionA -> binding.imageView1.setImageResource(R.drawable.image1)
               else -> //do something
            }

            //or
            
            when(position){
               0 -> binding.imageView1.setImageResource(R.drawable.image1)
               else -> //do something
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = ItemListRcvBinding.inflate(LayoutInflater.from(parent.context))
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = getItem(position)
        holder.bind(item,position)
    }

    override fun getItemCount(): Int = list.size
    
}

in activity/fragment

...
adapter = ItemListAdapter(myList1, object:  ItemListAdapter.OnItemClickListener{
        override fun onItemClick(view: View, position: Int){
         //do something
     }
   }

...
  • Related