如何在运行时修改xml中的颜色属性?

时间:2014-04-20 10:52:07

标签: android xml background

在我的安卓游戏中,有一个textview,其背景是一个灰色的圆圈。我通过在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"

/>

circle.xml在哪里

<?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>

现在我想根据用户输入更改背景圆的颜色。它有可能吗?如何?

1 个答案:

答案 0 :(得分:1)

您必须将TextView的背景作为GradientDrawable对象,然后更改其颜色:

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