user3293494
user3293494

Reputation: 609

How to modify color attribute in xml during runtime?

In my android game, there is a textview, whose background is a circle with gray color. I am achieving this by following code in xml.

 <TextView 
android:id="@+id/tv0"
android:textColor="#fff"
android:textStyle="bold"
android:background="@drawable/circle"
android:layout_gravity="left"
android:gravity="center_vertical|center_horizontal" 
android:layout_width="50dp"
android:layout_height="50dp"

/>

Where circle.xml is

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<solid android:color="#aaaaaa" /> 
<corners android:topLeftRadius="60dp" android:topRightRadius="60dp" android:bottomLeftRadius="60dp" android:bottomRightRadius="60dp" /> 
</shape>

Now I want to change the color of the background circle based on user input. Is it possible and how ?

Upvotes: 1

Views: 411

Answers (1)

belen
belen

Reputation: 296

You have to get the background of the TextView as a GradientDrawable object and then change its color:

TextView tv = (TextView) findViewById(R.id.tv0);
GradientDrawable gd = (GradientDrawable) tv.getBackground();
gd.setColor(0xFFFF99CC);

Upvotes: 1

Related Questions