DrawableCompat.unwrap在Lollipop之前无效

use*_*773 5 android tint drawable android-support-library android-5.0-lollipop

我正在使用DrawableCompat.wrap在pre Lollipop中为drawables设置色调,它工作正常.DrawableCompat.unwrap在Lollipop之前无效.在色调之前我无法获得原始的drawable.

例如:

 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);
 }
Run Code Online (Sandbox Code Playgroud)

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

eld*_*o87 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);
}
Run Code Online (Sandbox Code Playgroud)

你的情况下,代码应该是:

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);
}
Run Code Online (Sandbox Code Playgroud)