DrawableCompat.unwrap在Lollipop之前无效

时间:2015-06-19 19:02:32

标签: android android-5.0-lollipop drawable android-support-library tint

我正在使用DrawableCompat.wrap在pre Lollipop上的drawables上设置色调并且它工作正常。 DrawableCompat.unwrap在Lollipop之前无效。 我无法在色彩之前得到原始的可绘制。

例如:

 if (v.isSelected()){
                Drawable normalDrawable = getResources().getDrawable(R.drawable.sample);
                Drawable wrapDrawable = DrawableCompat.wrap(normalDrawable);
                DrawableCompat.setTint(wrapDrawable, getResources().getColor(R.color.sample_color));
                imageButton.setImageDrawable(wrapDrawable);
 }else{
                Drawable normalDrawable = imageButton.getDrawable();
                Drawable unwrapDrawable = DrawableCompat.unwrap(normalDrawable);
                imageButton.setImageDrawable(unwrapDrawable);
 }

在棒棒糖前设备中,DrawableCompact.unwrap返回带有色调的drawable,而不是原始的

1 个答案:

答案 0 :(得分:1)

如果要清除色调,请拨打DrawableCompat.setTintList(drawable, null)

Unwrap不是破坏性的功能,只有你才能访问原来的Drawable。

以下是示例代码

Drawable drawable = (Drawable) ContextCompat.getDrawable(getContext(), R.drawable.google_image);
if (condition) {
    drawable = DrawableCompat.wrap(drawable);
    DrawableCompat.setTint(drawable, ContextCompat.getColor(getContext(), R.color.grey700));
    DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SCREEN);
    mImageView.setImageDrawable(drawable);
} else {
    drawable = DrawableCompat.unwrap(drawable);
    DrawableCompat.setTintList(drawable, null);
    mLoginStatusGoogleImageView.setImageDrawable(drawable);
}

您的情况中,代码应为:

if (v.isSelected()) {
    Drawable normalDrawable = getResources().getDrawable(R.drawable.sample);
    Drawable wrapDrawable = DrawableCompat.wrap(normalDrawable);
    DrawableCompat.setTint(wrapDrawable, ContextCompat.getColor(getContext(), R.color.sample_color));
    DrawableCompat.setTint(wrapDrawable, getResources().getColor(R.color.sample_color));
    imageButton.setImageDrawable(wrapDrawable);
} else {
    Drawable normalDrawable = imageButton.getDrawable();
    Drawable unwrapDrawable = DrawableCompat.unwrap(normalDrawable);
    DrawableCompat.setTintList(unwrapDrawable, null);
    imageButton.setImageDrawable(unwrapDrawable);
}