0

Is there a technique to implement the Android app xml resources with variable in it?

For example: I have a app resource, i.e., res/drawable/rounded_corners.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@android:color/holo_blue_dark" />
    <corners android:radius="10dp" />
</shape>

It works, but I need to change the color in the runtime without creating a lot of similar resources like this just with different colors.

2 Answers 2

2

no option for changing XML, but any "kind" of XML have representation in code, layouts, values, drawables etc. So you can import your XML to code and change it there

fun fact you are using <shape so this should refer to ShapeDrawable, but thanks to THIS QA we do know that it is in fact GradientDrawable. Still under link you can find a way for "porting" your XML to code - make some "factory" or "helper" or whatever your style is and prepare in there properly colorised shapes for your Views, e.g. by taking color as param of some static method

Resources r = context.getResources();
GradientDrawable yourDrawable = 
    (GradientDrawable) (r.getDrawable(R.drawable.rounded_corners).mutate());
yourDrawable.setColor(color);

note mutate() call, it is important if you are reusing your shape many times. if you won't call it all existing instances of your shape will get color set lastly for last created/modified shape

edit: worth noting that such basic XML-defined shape as in question may be easily created with code only everytime is needed (without need for mutate() call). the purpose of XMLs is to fast load and apply them using built-in mechanisms in framework, they shouldn't be loaded and modified programmatically, at least not to often (as pure code will be always more efficient, at least a very little bit, than some parser, which will build code for you)

Sign up to request clarification or add additional context in comments.

Comments

1

Use java code instead of xml:

GradientDrawable gd = new GradientDrawable();
gd.setColor(fillColor);
gd.setCornerRadius(roundRadius);
gd.setStroke(strokeWidth, strokeColor);

Or generate drawable via that code than set color via casting

AppCompatResources.getDrawable(context, R.drawable.your_drawable)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.