Home > Blockchain >  Android app xml resources with variable in it?
Android app xml resources with variable in it?

Time:12-24

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.

CodePudding user response:

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

CodePudding user response:

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)
  • Related