0

I'm making a to-do app and I'm using a RecyclerView to create a multiple grid layout like this:

Grid layout image

I'm using a background layout to round the corners:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="6dp"  />
    <corners android:radius="20dp"/>
</shape>

My problem is that whenever I change the color dynamically in the adapter like this:

public void onBindViewHolder( ViewHolder holder, int position) {
   holder.timee.setBackgroundColor(task.get(position).getColor());
   holder.timee.setTextColor(Color.WHITE);
   holder.grid.setBackgroundColor(Color.WHITE);
   holder.namee.setTextColor(task.get(position).getColor());
}

The background color seems to ignore the boundaries I've set with the background layout and I get this result:

Background color ignoring boundaries image

What is the best way to make it have both rounded corners and a different color for every item in the RecycerView?

Bö macht Blau
  • 12,820
  • 5
  • 40
  • 61
Miltent
  • 185
  • 1
  • 9

2 Answers2

1

The background "layout" you are using is in fact not a layout at all; It is a drawable resource. This means that though the visible borders are rounded, the view itself still has its original shape.

When you set a background color programmatically, it replaces the previous drawable that had rounded corners and fills the entire rectangular view. In order to have both rounded corners, and a solid color fill within those bounds, you will need to modify your drawable itself. The <solid> tag should suit this purpose.

To support multiple colors, you can either have separate drawable resources for each of them (useful if you have just a couple of them), or you can use different tints on a base drawable. Other methods can be found at this question.

shriakhilc
  • 2,922
  • 2
  • 12
  • 17
0

This doesn't directly answer your question, but it offers an alternative that I find much easier to manage.

When I need views with rounded corners, I tend to use a CardView and I just remove the elevation. I can then modify the layout like any other programmatically:

<android.support.v7.widget.CardView
    android:layout_width="50dp"
    android:layout_height="50dp"
    card_view:cardBackgroundColor="#5500FF00"
    card_view:cardCornerRadius="10dp"
    card_view:cardElevation="0dp" />

So you just use the CardView in your list item view that's inflated, and then in your code you simply do this:

public void onBindViewHolder( ViewHolder holder, int position) {
   ...
   holder.cardView.setCardBackgroundColor(task.get(position).getColor());
   ...
}
AnxGotta
  • 1,006
  • 7
  • 28