banner
RustyNail

RustyNail

coder. 【blog】https://rustynail.me 【nostr】wss://ts.relays.world/ wss://relays.world/nostr

TextView Dynamically Change the Background Color of Drawables

When encountering the need to dynamically change the color of a Drawable, record the following:

Create a shape in /drawble/t_shape.xml

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

Then, you need to dynamically change the color.

First, you need to obtain the Drawable.

Drawable tagShapeDrawable = Drawable.createFromXml(context.getResources(), context.getResources().getXml(R.drawable.tag_shape));

Then,

tagShapeDrawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
view.setBackground(tagShapeDrawable);
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.