-1

I have a RecyclerView adapter that sets the icon for every item on the list. Here's the adapter class

package m.e.myapplication

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.calculator_cost_currency_type_item.view.*

class CurrencyTypeAdapter: RecyclerView.Adapter<CurrencyTypeViewHolder>() {

private val currencyTypeList = listOf(R.drawable.icon_currency_dollar, R.drawable.icon_currency_euro, R.drawable.icon_currency_lira)

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

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CurrencyTypeViewHolder {
    val layoutInflater = LayoutInflater.from(parent.context)
    val cellForRow = layoutInflater.inflate(R.layout.calculator_cost_currency_type_item, parent, false)
    return CurrencyTypeViewHolder(cellForRow)
}

override fun onBindViewHolder(holder: CurrencyTypeViewHolder, position: Int) {
    val currencyTypeItem = currencyTypeList[position]

    holder.itemView.currencyTypeItemCostImageViewCCF.setImageResource(currencyTypeItem)
}
}

class CurrencyTypeViewHolder(view: View): RecyclerView.ViewHolder(view) {
}

Here's how it's being called from the MainActivity

package m.e.myapplication

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    currencyTypeRecyclerViewCCF.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
    currencyTypeRecyclerViewCCF.adapter = CurrencyTypeAdapter()
    }
}

I would like to have code that changes the color of the layout corresponding to the selected item, as well as code that changes the color of the unselected items. Thanks in advance

Ever
  • 43
  • 5

1 Answers1

0

First of all create string type variable name it selectedposition var selectedposition=""in your CurrencyTypeAdapter class

Now add position tag to your itemview holder.itemview.tag="$position" //this is for to identify the itemview

Now add onClick listener to your itemview in onBindViewHolder method holder.itemView.setOnClickListener{ selectedposition="$position" notifyDataSetChanged() }

Now in onBindViewHolder method if(selectedposition.equal("$position")){ //this is your selected item do what you want }

Rahul sharma
  • 1,492
  • 12
  • 26