Android - 动态设置可绘制的渐变

Sam*_*uel 6 java android

我有一个来自 XML 资源的 drawable,我想使用该 drawable 但动态设置渐变颜色。到目前为止,我有这样的事情:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="3dip">
    </corners>
    <gradient
        android:angle="90"
        android:type="linear"
        android:startColor="#FFFFFFFF"
        android:centerColor="#FFFF0000"
        android:endColor="#FFFF0000">
    </gradient>
</shape>
Run Code Online (Sandbox Code Playgroud)

现在我想我可以通过在运行时获取可绘制对象、将其转换为 GradientDrawable 并使用一种方法来设置颜色来动态制作颜色。但是 GradientDrawable 没有这样的方法,只能在构造函数中设置颜色。我觉得这种情况很奇怪,因为渐变的所有其他方面都是可以设置的。有没有比覆盖 onDraw() 并自己做渐变更简单的方法?我尝试使用的一些类的记录非常差..

ila*_*o j 0

您可以动态地将视图设置为可绘制背景。

view.setBackgroundDrawable(R.drawable.your_drawable_id);