如何在appcompat 23.3.0中更改按钮的可绘制颜色?

5

我在使用新的AppCompat 23.3.x和可绘制对象时遇到了一些问题。首先,我不得不回去删除:

vectorDrawables.useSupportLibrary = true

因为AppCompat进行了还原,所以现在我的应用程序再次生成PNG。好的,然而,我正在以一种方式给一个按钮(drawableTop)添加着色,但这种方法在M之前的设备上完全无法工作。
以下是我使用的方法:
private void toggleState(boolean checked) {
    Drawable[] drawables = getCompoundDrawables();
    Drawable wrapDrawable = DrawableCompat.wrap(drawables[1]);
    if (checked) {
        DrawableCompat.setTint(wrapDrawable.mutate(), ContextCompat.getColor(getContext(),
                R.color.colorPrimary));
        setTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
    } else {
        DrawableCompat.setTint(wrapDrawable.mutate(), ContextCompat.getColor(getContext(),
                R.color.icon_light_enabled));
        setTextColor(ContextCompat.getColor(getContext(), R.color.text_primary_light));
    }
}

问题是,我有一个自定义的Button类,它可以被选中,如果选中了,drawableTop和文本的颜色与未选中时不同。

这个方法之前是有效的(使用appcompat 23.2.0),但现在(在Android M以下)已经无效了。你可以相信或者不相信,但当它执行setTint方法时,图标将完全不可见。

要使其正常工作,我必须按照以下步骤操作:

 DrawableCompat.setTint(wrapDrawable.mutate(), ContextCompat.getColor(getContext(),R.color.colorPrimary));
 setCompoundDrawablesWithIntrinsicBounds(null, wrapDrawable, null, null);

每次我在它们上面涂色时,都必须再次调用setCompoundDrawablesWithIntrinsicBounds。这样做可以使一切重新运作。但是,我有点担心每次设置绘制内容的性能。基本上,我想知道是否有更好的方法或者我是否遗漏了什么东西。
我知道一个Button具有setCompoundDrawableTintList,这将非常棒,但其最小API级别为23级。

这与VectorDrawable有什么关系? - pskink
1
我相信你 - 它是不可见的。用着色后的可绘制对象替换原来的可绘制对象就解决了问题。感谢ContextCompat.getColor(getContext(),R.color.colorPrimary) - Justin Case
1个回答

4

我的声望不够高,因此无法发表评论,但我也遇到了这个问题。这真的很糟糕,很幸运我今天意识到了这个问题,而不是在发布后才发现。

/**
 * Tinting drawables on Kitkat with DrawableCompat
 * requires wrapping the drawable with {@link DrawableCompat#wrap(Drawable)} prior to tinting it
 * @param view The view containing the drawable to tint
 * @param tintColor The color to tint it.
 */
public static void tintViewBackground(View view, int tintColor) {
    Drawable wrapDrawable = DrawableCompat.wrap(view.getBackground());
    DrawableCompat.setTint(wrapDrawable, tintColor);
    view.setBackground(wrapDrawable);
}

/**
 * Tinting drawables on Kitkat with DrawableCompat
 * requires wrapping the drawable with {@link DrawableCompat#wrap(Drawable)} prior to tinting it
 * @param drawable The drawable to tint
 * @param tintColor The color to tint it.
 */
public static void tintDrawable(Drawable drawable, int tintColor) {
    Drawable wrapDrawable = DrawableCompat.wrap(drawable);
    DrawableCompat.setTint(wrapDrawable, tintColor);
}

更奇怪的是,这仅会在Lollipop上发生,而在Kitkat和API 23+上看到正常行为。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接