Naujas Tewas
Naujas Tewas

Reputation: 73

Programmatically change colors in drawable xml file

I need to change my application's colors during runtime. I parse data file to get colors and I save it in class with static fields and methods:

public class Colors {

    private static String colorOneBackground = "#00577F";
    private static String colorOneForeground = "#FFFFFF";

    public static void setColorOneBackground(String colorOneBackground) {
        Colors.colorOneBackground = colorOneBackground;
    }

    public static int getColorOneForeground() {
        return Color.parseColor(colorOneForeground);
    }
    // more colors...

Then, for example when I want to change the background of screen I do it so:

RelativeLayout relativeLayout = (RelativeLayout) myView.findViewById(R.id.loginBackground);
        relativeLayout.setBackgroundColor(Colors.getColorOneBackground());

Same with textviews and other widgets. However, I have encountered one problem. Some styles are defined in Drawable folder, for example, mybutton.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android=" http://schemas.android.com/apk/res/android "
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFFFF"
        android:centerColor="#FFFFFF"
        android:endColor="#FFFFFF"
        android:angle="270" />
    <corners android:radius="5dp" />
    <stroke android:width="3px" android:color="#000000" />
</shape>

And I set this as my button's background:

<Button  
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:id="@+id/title"
   android:background="@drawable/mybutton" />

As I said I want to change these color values programatically. So I want to know if it is possible to dinamically change color values defined in xml file?

Upvotes: 0

Views: 4108

Answers (1)

rafsanahmad007
rafsanahmad007

Reputation: 23881

try this : to change color in your drawable xml file:

button.setBackgroundResource(R.drawable.mybutton);  //drawable id
GradientDrawable gd = (GradientDrawable) button.getBackground().getCurrent();
gd.setColor(Color.parseColor("#000000")); //set color
gd.setStroke(2, Color.parseColor("#00FFFF"), 5, 6);

Upvotes: 3

Related Questions