Rehan Yousaf
Rehan Yousaf

Reputation: 765

How to change background/color of the drawable set as background of a view?

I have this xml in my drawables folder.

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="10dp"/>
    <solid android:color="#ffffff"/>
</shape>

I am basically using this to have round corners for any views that I set this as a background of. But what I want to know is how I can keep the color/background tint of that view dynamic. Because lets say I have three views which all need to be round cornered but all need to be of different color, at the minute I am having to create three different drawable files and set color to each file separately. As I've done in the file above. I've tried using BackgroundTint on the original view but it doesn't work.

Upvotes: 2

Views: 2003

Answers (2)

FarshidABZ
FarshidABZ

Reputation: 4123

Create a Drawable background and set your view background:

private void setBackground(View v, int backgroundColor) {
    GradientDrawable shape = new GradientDrawable();
    shape.setShape(GradientDrawable.RECTANGLE);
    shape.setColor(backgroundColor);
    shape.setSize(width, height);
    shape.setCornerRadius(4.0f);
    v.setBackground(shape);
    v.setBackgroundDrawable(shape);
}

Upvotes: 3

Chirag
Chirag

Reputation: 56925

GradientDrawable background = (GradientDrawable) textView.getBackground();
background.setColor(getResources().getColor(R.color.some_color));

I have considered that you have applied your shape drawable to textView as background.

So you need to use your view in which you have set your background to get background.

Upvotes: 5

Related Questions