How to programmatically round corners and set random background colors

android, android-layout, android-view, background, rounded-corners

Solution

Instead of `setBackgroundColor`, retrieve the background drawable and set its color:

v.setBackgroundResource(R.drawable.tags_rounded_corners);

GradientDrawable drawable = (GradientDrawable) v.getBackground();
if (i % 2 == 0) {
  drawable.setColor(Color.RED);
} else {
  drawable.setColor(Color.BLUE);
}

Also, you can define the padding within your `tags_rounded_corners.xml`:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <corners android:radius="4dp" />
  <padding
    android:top="2dp"
    android:left="2dp"
    android:bottom="2dp"
    android:right="2dp" />
</shape> 

Problem

I'd like to round the corners of a view and also change the color of the view based on the contents at runtime. ``` TextView v = new TextView(context); v.setText(tagsList.get(i)); if(i%2 == 0){ v.setBackgroundColor(Color.RED); }else{ v.setBackgroundColor(Color.BLUE); } v.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); v.setPadding(twoDP, twoDP, twoDP, twoDP); v.setBackgroundResource(R.drawable.tags_rounded_corners); ``` I was hoping setting a drawable and color would overlap, but they do not. Whichever one I execute second is the resulting background. Is there any way to programmatically create this view, keeping in mind that the background color won't be decided until runtime? edit: I'm only swapping between red and blue now for testing. Later the color will be choosable by the user. edit: tags_rounded_corners.xml: ``` <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <corners android:bottomRightRadius="2dp" android:bottomLeftRadius="2dp" android:topLeftRadius="2dp" android:topRightRadius="2dp"/> </shape> ```

Original source