How to change TextView's background color dynamically?

5.9k Views Asked by At

I have reffered this question and implemented circular background for TextView using circle.xml (in res/drawable) and setting it as android:background="@drawable/circle" for TextView. But what I need is , I need to set the background color dynamically through code. Just like the lollipop contacts app as shown below

enter image description here

How can I acheive this? I need the TextView background in circular shape always as shown in above image

3

There are 3 best solutions below

6
On BEST ANSWER

You can change TextView background color in many ways like:

textView.setBackgroundColor(Color.parseColor("#f44336"));

or

textView.setBackgroundColor(Color.RED);

or

textView.setBackgroundColor(Color.rgb(255, 0, 0));

or

textView.setBackgroundColor(getColor(R.color.red_color));

and many other ways too...

Edit:

If you want to change your TextView background color that was defined in your drawable file, do it like this:

GradientDrawable:

GradientDrawable tvBackground = (GradientDrawable) textView.getBackground();
tvBackground.setColor(Color.parseColor("#f44336"));

StateListDrawable:

StateListDrawable tvBackground = (StateListDrawable) textView.getBackground();
tvBackground.setColorFilter(Color.parseColor("#f44336"), PorterDuff.Mode.SRC_ATOP);

But if you don't want to set a color filter, you can get the drawable of each state separately by following the answer in this link.

0
On

My text view has a circle shape defined as

// circleshape.xml

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="schemas.android.com/apk/res/android"; android:shape="oval"> 
<solid android:color="@android:color/darker_gray" /> 
<corners android:bottomRightRadius="8dp" android:bottomLeftRadius="8dp" android:topRightRadius="8dp" android:topLeftRadius="8dp"/> 
</shape>

I applied it to Textview using background="@drawable/circleshape"

This makes the textview circular. Now use the code below to

GradientDrawable tvBackground = (GradientDrawable) viewHolder.userInitialsText.getBackground();

//myHexColorCode  is like "0xff00ff"
tvBackground.setColor(Color.parseColor(myHexColorCode));
1
On

I think you wanted to ask how to generate random color to set as your textview background. Well, there are many ways. e.g;

textview.setBackgroundColor(Color.rgb((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)));