我使用以下行更改VectorDrawable的颜色:
mydrawable.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
这很好用,尽管现在已弃用。该文档建议我使用:
mydrawable.getBackground().setColorFilter(new BlendModeColorFilter(color, PorterDuff.Mode.SRC_ATOP))
尽管,BlendModeColorFilter
仅在API29上可用。在检查了不赞成使用的方法的源之后,我意识到它调用了:
new PorterDuffColorFilter()
所以,我继续使用:
mydrawable.getBackground().setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP))
着色起作用。这是不推荐使用的方法的正确替代方法,还是我必须在API29上使用BlendModeColorFilter?
谢谢。
答案 0 :(得分:11)
使用androidx.core:core:1.2.0-beta01
或androidx.core:core-ktx:1.2.0-beta01
。
// Java
implementation 'androidx.core:core:1.2.0-beta01'
// Kotlin
implementation 'androidx.core:core-ktx:1.2.0-beta01'
这:
drawable.setColorFilter(BlendModeColorFilterCompat.createBlendModeColorFilterCompat(color, BlendModeCompat.SRC_ATOP))
答案 1 :(得分:6)
尝试一下:
public class MyDrawableCompat {
public static void setColorFilter(@NonNull Drawable drawable, int color) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
drawable.setColorFilter(new BlendModeColorFilter(color, BlendMode.SRC_ATOP));
} else {
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
}
}
}
这:
MyDrawableCompat.setColorFilter(mydrawable.getBackground(), color);
答案 2 :(得分:0)
由于@shmakova,我为Kotlin添加了一个解决方案。
import android.graphics.BlendMode
import android.graphics.BlendModeColorFilter
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.os.Build
fun Drawable.setColorFilter(color: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
this.colorFilter = BlendModeColorFilter(color, BlendMode.SRC_ATOP)
} else {
@Suppress("DEPRECATION")
this.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
}
}
fun Drawable.setColorFilter(color: Int, blendMode: BlendMode, porterMode: PorterDuff.Mode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
this.colorFilter = BlendModeColorFilter(color, blendMode)
} else {
@Suppress("DEPRECATION")
this.setColorFilter(color, porterMode)
}
}
照常使用:
toolbar?.navigationIcon?.setColorFilter(ContextCompat.getColor(this, color))
我使用诸如BlendMode.SRC_IN
,SRC_OUT
,SRC_OVER
之类的参数调用了第二种方法:
drawable.setColorFilter(color, BlendMode.SRC_ATOP, PorterDuff.Mode.SRC_ATOP)
但收到此异常:
原因:java.lang.ClassNotFoundException:未找到类 路径上的“ android.graphics.BlendMode”:DexPathList [[zip文件 “ /data/app/com.....debug-Rqe9xWr93dJ0K20ebcBM3g==/base.apk"],nativeLibraryDirectories=[/data/app/com....debug-Rqe9xWr93dJ0K20ebcBM3g==/lib/x86, / system / lib,/ vendor / lib]]
但是,当将它们而不是参数插入函数主体时,我没有收到异常。