Reputation: 301
I have an issue, I want to have the recycler item row color alternatively. ie, If 1st row is in white color, 2nd row is in grey color and 3rd row is again white and 4th is again grey and so on. I tried one code, but it didn't work. Kindly help.
This is my code,
class ItemAdapter() : RecyclerView.Adapter<ItemAdapter.DateViewHolder>() {
private var ItemList: MutableList<Items>? = ArrayList()
private lateinit var ItemViewModel: ItemRowListBinding
private lateinit var listener: OnItemClickListener
init {
this.ItemList = arrayListOf()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DateViewHolder {
ItemViewModel = DataBindingUtil.inflate(
LayoutInflater.from(parent.context), R.layout.item_row_list,
parent, false
)
return DateViewHolder(ItemViewModel)
}
override fun onBindViewHolder(holder: DateViewHolder, position: Int) {
if(position % 2 == 0) {
holder.itemView.setBackgroundResource(R.color.White);
} else {
holder.itemView.setBackgroundResource(R.color.Grey);
}
holder.bindItemDetail(ItemList!![position])
}
override fun getItemCount(): Int {
return ItemList!!.size
}
fun setItemList(scanList: MutableList<Items>) {
this.ItemList = scanList
notifyDataSetChanged()
}
inner class DateViewHolder(private var itemRowBinding: ItemRowListBinding) :
RecyclerView.ViewHolder(itemRowBinding.root) {
fun bindItemDetail(ItemResponse: Items) {
if (itemRowBinding.ItemDetailViewModel == null) {
itemRowBinding.ItemDetailViewModel =
ItemDetailViewModel(
ItemResponse,
itemView.context
)
} else {
itemRowBinding.ItemDetailViewModel!!.setDetail(ItemResponse)
itemRowBinding.executePendingBindings()
}
itemRowBinding.root.Detail.setOnClickListener {
notifyDataSetChanged()
}
itemRowBinding.root.itemLookup.setOnClickListener {
Log.v(
"Clicked_ADAPTER",
"Clicked itemLookup adapter :: position -> $adapterPosition"
)
}
}
}
Any help would be deeply appreciated.
Upvotes: 0
Views: 561
Reputation: 6089
If you want to set the drawable you can use setBackgroundResource
Here you are trying to give color in setBackgroundResouce so it is not giving the result
You can set background color using setBackgroundColor
if(position % 2 == 0) {
holder.itemView.setBackgroundColor(ContextCompat.getColor(context,R.color.White));
} else {
holder.itemView.setBackgroundColor(ContextCompat.getColor(context,R.color.Grey));
}
Upvotes: 1
Reputation: 791
If you read setBackgroundDrawable's documentation, it expects a Drawable
resource ID, or 0
to clear the background. A Color
is not a Drawable
. So you probably want to use this:
holder.itemView.setBackgroundColor(ContextCompat.getColor(context,R.color.white))
Upvotes: 2
Reputation: 164
Try this : It worked for me.
if(position % 2 == 0){
holder.itemView.setBackgroundColor(#A6A2A2);
}else{
holder.itemview.setBackgroundColor(#FFFFFF);
}
Upvotes: 0