我想基本上创建API 21+ tint
xml属性的“支持”版本。如何在代码中从drawable中获取tint
属性(或自定义属性),而不为每个图像使用自定义View
?
这是/res/drawable/brandable_icon_slider_featured.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tintns="http://schemas.android.com/apk/res-auto"
android:src="@drawable/brandable_icon_slider_featured_img"
tintns:tintColor="@color/branded_menu" />
然后,我创建了一个自定义Resources
子类,并在我的“活动”中使用它。
public class CustomResource extends Resources {
...
@Override
public XmlResourceParser getXml(int id) throws NotFoundException {
XmlResourceParser parser = super.getXml(id);
return parser;
}
@Override
public Drawable getDrawableForDensity(int id, int density) throws NotFoundException {
return replaceWithTintableBitmap(super.getDrawableForDensity(id, density));
}
@Override
public Drawable getDrawableForDensity(int id, int density, Theme theme) {
return replaceWithTintableBitmap(super.getDrawableForDensity(id, density, theme));
}
@Override
public Drawable getDrawable(int id) throws NotFoundException {
return replaceWithTintableBitmap(super.getDrawable(id));
}
@Override
public Drawable getDrawable(int id, Theme theme) throws NotFoundException {
return replaceWithTintableBitmap(super.getDrawable(id, theme));
}
private Drawable replaceWithTintableBitmap(Drawable drawable) {
if(drawable instanceof BitmapDrawable) {
return new TintableBitmap(this, (BitmapDrawable) drawable);
}
return drawable;
}
}
当然,我的TintableBitmap
类扩展了BitmapDrawable
,它会将tint
属性“转换”为drawable.setColorFilter
调用,该调用具有向后支持。
我尝试使用自定义属性无济于事。
<!-- attrs.xml -->
<declare-styleable name="TintTheme">
<attr name="tintColor" format="color" />
</declare-styleable>
<!-- themes.xml -->
<style name="BaseTheme" parent="android:style/Theme.Light.NoTitleBar">
<item name="tintColor">#fff</item>
</style>
那么,是否可以在tint
或CustomResource
中检测并获取TintableBitmap
属性的值?