在运行时更改颜色资源

时间:2012-08-08 06:58:52

标签: android

是否可以从res-colors.xml更改颜色:

<color name="transparent_color">#00000000</color>

在运行时?

更改它的原因是,在我的扩展EditText上,我设置了这样的背景:

        setBackgroundResource(R.drawable.edittext_rounded_corners);

edittext_rounded_corners.xml看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/edittext_rounded_corners.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="true"><shape>
            <solid android:color="#FF8000" />
            <stroke android:width="2.3dp" android:color="@color/referenceFrame" />
            <corners android:radius="8dp" />
        </shape></item>
    <item android:state_focused="false" android:state_pressed="true"><shape>
            <solid android:color="#FF8000" />
            <stroke android:width="2.3dp" android:color="#FF8000" />
            <corners android:radius="8dp" />
        </shape></item>
    <item android:state_focused="true" android:state_pressed="false"><shape>
            <solid android:color="#FFFFFF" />
            <stroke android:width="2.3dp" android:color="#FF8000" />
            <corners android:radius="8dp" />
        </shape></item>
    <item android:state_focused="false" android:state_pressed="false"><shape>
            <gradient android:angle="270" android:centerColor="#FFFFFF" android:endColor="#FFFFFF" android:startColor="#F2F2F2" />
            <stroke android:width="0.7dp" android:color="#BDBDBD" />
            <corners android:radius="8dp" />
        </shape></item>
    <item android:state_enabled="true"><shape>
            <padding android:bottom="4dp" android:left="4dp" android:right="4dp" android:top="4dp" />
        </shape></item>

</selector>

当我在其中出现错误时,我需要一种方法使@Color / referenceFrame变红。已经完成了错误处理,只需要一种方法来改变参考框架

1 个答案:

答案 0 :(得分:1)

创建一个新的drawable(或选择器,你需要的),referenceFrame设置为红色。 我们调用此文件edittext_error.xml

然后,当您遇到错误时,只需将EditText的背景更改为指向新文件:

setBackgroundResource(R.drawable.edittext_error);