像 Support NavigationView 中的图标着色

Tinting of icons like in the Support NavigationView

NavigationView 会对图标进行 颜色着色(如果图标有颜色)。 我的图标是绿色的,在 NavigationView 中它是 灰色 。这是如何工作的?

我想自己在另一个视图中执行此操作,但我没有找到 NavigationView 是如何执行此操作的。

blog post 解释了可绘制对象的 AppCompat 着色。这是您要找的吗?

The Drawable tinting methods added in Lollipop are super useful for letting you dynamically tint assets. AppCompat had its own baked in implementation in the v21 support library and we’ve now extracted that into DrawableCompat in support-v4 for everyone to use. It’s important to know how it works though.

Drawable drawable = ...;

// Wrap the drawable so that future tinting calls work 
// on pre-v21 devices. Always use the returned drawable.
drawable = DrawableCompat.wrap(drawable);

// We can now set a tint 
DrawableCompat.setTint(drawable, Color.RED);
// ...or a tint list 
DrawableCompat.setTintList(drawable, myColorStateList);
// ...and a different tint mode
DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_OVER);

或者如果你只想给 ImageView 着色,你可以这样做:

ImageView image = (ImageView) findViewById(R.id.image);
image.setColorFilter(...);