色调一个 drawable

可绘制的颜色可以着色。这对于支持应用程序中的不同主题以及减少可绘制资源文件的数量非常有用。

在 SDK 21+上使用框架 API:

Drawable d = context.getDrawable(R.drawable.ic_launcher);
d.setTint(Color.WHITE);

在 SDK 4+上使用 android.support.v4 库:

//Load the untinted resource
final Drawable drawableRes = ContextCompat.getDrawable(context, R.drawable.ic_launcher);
//Wrap it with the compatibility library so it can be altered
Drawable tintedDrawable = DrawableCompat.wrap(drawableRes);
//Apply a coloured tint
DrawableCompat.setTint(tintedDrawable, Color.WHITE);
//At this point you may use the tintedDrawable just as you usually would 
//(and drawableRes can be discarded)

//NOTE: If your original drawableRes was in use somewhere (i.e. it was the result of 
//a call to a `getBackground()` method then at this point you still need to replace 
//the background. setTint does *not* alter the instance that drawableRes points to, 
//but instead creates a new drawable instance

请注意,int color 不是指颜色资源,但你不限于颜色类中定义的那些颜色。当你在 XML 中定义了要使用的颜色时,你必须首先获得它的值。

你可以使用以下方法替换 Color.WHITE 的用法

在定位较旧的 API 时:

getResources().getColor(R.color.your_color);

或者在新目标上:

ContextCompat.getColor(context, R.color.your_color);