如何通过编程更改gradient-Android的startColor属性

如何通过编程更改gradient-Android的startColor属性,android,shape,Android,Shape,我有一个在布局中使用的形状。我希望在活动中以编程方式更改颜色 <shape android:id="@+id/shape1" xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:id="@+id/gradient1" android:startColor="@color/widget_header"

我有一个在布局中使用的形状。我希望在活动中以编程方式更改颜色

<shape android:id="@+id/shape1" xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
   <gradient android:id="@+id/gradient1"
        android:startColor="@color/widget_header"
        android:endColor="#0000CC" 
        android:angle="270"/> 

   <corners android:bottomRightRadius="1dp"
        android:bottomLeftRadius="1dp" 
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/> 
</shape>


有什么方法可以更改活动中的“startColor”和“endColor”属性吗?

请检查,有很多附加代码,但它似乎演示了如何创建可绘制和渐变可绘制的代码。。。看看第159行。您可能不需要在XML中创建形状,因为您可能需要以编程方式创建形状等

Kotlin代码,以更改现有渐变可绘制文件的开始颜色和结束颜色: GradientDrawable文件示例(gradient_header.xml):

*如果视图在当前活动中,只需使用其id,而不是膨胀

2-如果将渐变应用于ViewwGroup对象(ConstraintLayout,LinearLayout,…)的背景,则可以从膨胀的XML中这样访问它,如果布局为ConstraintLayout,则示例如下:

   val  rootConstraintLayout= layoutFile.findViewById< ViewGroup  >(R.id.root_constraintlayout_ly_custom_header)
rootConstraintLayout.background =  drawable
4-更改/设置开始和结束颜色:

   drawable.colors = intArrayOf(   startColor , endColor  )
5-将dawable应用于视图(此处为CONSTRAINTLAOUT):

  • 如果您的颜色为六边形,则可以使用此选项转换颜色:

    var startColor=Color.parseColor(#92A8F1) 或者简单地使用您的颜色:

    var startColor=Color.BLUE


在这里,我想我会找到一些有一页代码的东西,然后看看159,而不是大量的代码。
   val  rootConstraintLayout= layoutFile.findViewById< ViewGroup  >(R.id.root_constraintlayout_ly_custom_header)
 var drawable  = rootConstraintLayout.background as GradientDrawable
   drawable.colors = intArrayOf(   startColor , endColor  )
rootConstraintLayout.background =  drawable