How to change the color of layout from ViewHolder in Android?

1176 views android
3

I passed the color resourses to a Class which held the List Items as

package com.example.mythio.todoo;

public class ListElement {

private String todo;
private String todoDate;
private int todoPriority;

public ListElement(String todo, String todoDate, int todoPriority) {
    this.todo = todo;
    this.todoDate = todoDate;
    this.todoPriority = todoPriority;
}

public String getTodo() {
    return todo;
}

public String getTodoDate() {
    return todoDate;
}

public int getTodoPriority() {
    return todoPriority;
}
}

todoPriority is holding the color passed stored in the colors.xml

I passed the color as

    todoList.add(new ListElement("Task 1", "29 September 1999", R.color.priority1));
    todoList.add(new ListElement("Task 1", "29 September 1999", R.color.priority2));

In my viewHolder,

@Override
public void onBindViewHolder(@NonNull mViewHolder holder, int position) {
    ListElement curr = todoList.get(position);
    holder.layout.setBackgroundColor(curr.getTodoPriority());
    holder.todo.setText(todoList.get(position).getTodo());
    holder.todoDate.setText(todoList.get(position).getTodoDate());
}

But it is not changing the color, I tried parsing the color and it worked, But how can i use the colors stored in 'colors.xml' to change the color?

answered question

1 Answer

10

From my point of knowledge , You can get Color using the below code by passing the context from the activity in which adapter is called as a parameter :

ContextCompat.getColor(context, R.color.your_color);

Below code can be used for both pre and post Marshmallow (API 23)

ResourcesCompat.getColor(getResources(), R.color.your_color, null); //without theme ResourcesCompat.getColor(getResources

posted this

Have an answer?

JD

Please login first before posting an answer.