问题
i need to chage color of shape drawable programatically...
i am using this
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="@color/app_theme_blue" />
<corners android:radius="8dp" />
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape>
Here i required to change color of android:color="@color/app_theme_blue"
.
please help me.
回答1:
Yes, you can. And it's really super easy.
First of all, keep in mind that it's easier to work with white images, in order to have a neutral source to apply the colour to (so, imagine to have a white contour on a transparent background).
Drawable drw = mContext.getResources().getDrawable(R.id.baseDrawable);
What this line does is simply getting the Drawable from the resources (baseDrawable - name it whatever you like).
Next, we're going to use an overload of the setColorFilter() method which accetpts two parameters: the color we want and the blending mode.
Note that the Drawable is unmutable by default, so we have to make it mutable, in order to apply any transformations to it.
drw.mutate().setColorFilter(finalColor, PorterDuff.Mode.MULTIPLY);
Now you can concentrate on your software, without the need to make many variations of the same resource.
By the way, there's no API Level requirement, it works since API Level 1.
P.S.:
These are the required imports:
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
来源:https://stackoverflow.com/questions/24166092/chagnge-color-of-shape-drawable-programatically