如何在Android上的Drawable资源上获取属性?

Dav*_*man 5 android android-layout android-resources

我想基本上创建API 21+ tintxml属性的"支持"版本.如何tint在代码中从drawable 获取属性(或自定义属性),而不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" />
Run Code Online (Sandbox Code Playgroud)

然后我创建了一个自定义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;
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,我的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>
Run Code Online (Sandbox Code Playgroud)

那么,是不是可以检测并获得的价值tint属性,无论是在CustomResourceTintableBitmap