Issue
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
Solution
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
In Kotlin
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)
}
In Java
public class TaskViewHolder extends RecyclerView.ViewHolder {
ImageView priorityIndicator;
public TaskViewHolder(@NonNull View itemView) {
super(itemView);
priorityIndicator = itemView.findViewById(R.id.priorityIndicator);
}
private void bind(Task task) {
int drawableId;
switch (task.priority) {
case 1: drawableId = R.drawable.indicator_red;
break;
case 2: drawableId = R.drawable.indicator_yellow;
break;
default: drawableId = R.drawable.indicator_green;
}
priorityIndicator.setImageDrawable(
ContextCompat.getDrawable(priorityIndicator.getContext(), drawableId)
);
}
}
Now call it from onBindViewHolder
@Override
public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) {
holder.bind(taskList.get(position));
}
Answered By - Praveen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.