When you call wrap()
then the original Drawable
is wrapped internally into a new DrawableWrapper
which is used to implement the tinting on older devices. So to make it work you have to set the returned Drawable
back to the EditText
:
final Drawable originalDrawable = editText.getBackground();
final Drawable wrappedDrawable = DrawableCompat.wrap(originalDrawable);
DrawableCompat.setTintList(wrappedDrawable, ColorStateList.valueOf(Color.RED));
editText.setBackground(wrappedDrawable);
Since version 23.2.0 of the support library you can also use setTint()
instead of setTintList()
to set just one tint color without having to create a ColorStateList
.
DrawableCompat.setTint(wrappedDrawable, Color.RED);
If you want to ensure backwards compatibility beyond API level 16 you run into a little snag. setBackground()
was added in API level 16 and you need to call setBackgroundDrawable()
on devices before that. It's best to implement a helper method which does that for you:
public static void setBackground(View view, Drawable background) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(background);
} else {
view.setBackgroundDrawable(background);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…