Anders Metnik
Anders Metnik

Reputation: 6247

Changing a color resource at runtime

Is it possible to change a color from res - colors.xml :

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

On runtime?

Reason for changing it is that, on my extended EditText I set my backgroundresouce like this:

        setBackgroundResource(R.drawable.edittext_rounded_corners);

edittext_rounded_corners.xml looks like this:

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

And I need a way to make the @Color/referenceFrame red, when I have an error in it. Have the error handling done already, just need a way to change reference frame

Upvotes: 1

Views: 1554

Answers (1)

Andy Res
Andy Res

Reputation: 16043

Create a new drawable (or selector, what you need) with the referenceFrame set to color red. Let call this file edittext_error.xml

Then when you encounter the error just change the background of your EditText to point to the newly file:

setBackgroundResource(R.drawable.edittext_error);

Upvotes: 1

Related Questions