I have a list of items displayed in Recycler view and they are sorted according to their priority (1,2,3) entered by the user with 1 on top and 3 at the bottom. I want the items to be accompanied by a drawable in red(for priority 1), yellow(for priority 2) and green(for priority 3) depending on the input from the user. May I please know how to display the drawable in such a case. picture 1
CodePudding user response:
So the color of the layout is always the same right? Red for 1st index, yellow for 2nd, and green for 3rd?
On your RecyclerView adapter you can pass a position parameter at onBindViewHolder
and add condition based on the position. For example:
override fun onBindViewHolder(holder: listHolder, position: Int) {
holder.bind(listItem[position], position)
}
class ListHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
fun bind(item: YourItem, position) {
when(position){
0 -> binding.imageView.setImageResource(R.drawable.redDrawable)
1 -> binding.imageView.setImageResource(R.drawable.yellowDrawable)
2 -> binding.imageView.setImageResource(R.drawable.greenDrawable)
}
}
}
CodePudding user response:
You can do this in onBindViewHolder
method of the adapter or create a bind
method in your view holder and then call it from onBindViewHolder
For the latter, in your view holder create bind method
class TaskViewHolder(private val taskItemBinding: TaskItemBinding) :
RecyclerView.ViewHolder(taskItemBinding.root) {
fun bind(task: Task) {
taskItemBinding.apply {
priorityIndicator.setImageDrawable(
ContextCompat.getDrawable(
priorityIndicator.context,
when (task.priority) {
1 -> R.drawable.indicator_red
2 -> R.drawable.indicator_yellow
3 -> R.drawable.indicator_green
}
)
)
}
}
}
Now, call it from onBindViewHolder
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
val task = getItem(position)
holder.bind(task)
}