Kotlin Code for change startColor & endColor of existed gradient drawable file :
Sample GradientDrawable file (gradient_header.xml):
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<gradient
android:angle="180"
android:startColor="@color/StartColor"
android:endColor="@color/EndColor"
android:type="linear" />
<corners
android:radius="0dp"/>
And the View(ViewGroup) that use this as background inside XML layout file (ly_custom_header.xml ):
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:background="@drawable/gradient_header"
android:layout_height="80dp"
android:id="@+id/rootConstraintLayout">
1- Inflate the layout XML ( file : ly_custom_header ) if it is not inside current activity/fragment context:
val layoutFile = View.inflate(this, R.layout.ly_custom_header, null)
* if the view is inside the current activity simply just use its id instead of inflating.
2- If you applied the gradient to the background of the ViewwGroup Object (ConstraintLayout, LinearLayout ,...), access it like this from inflated XML , for sample if our layout is ConstraintLayout :
val rootConstraintLayout= layoutFile.findViewById< ViewGroup >(R.id.root_constraintlayout_ly_custom_header)
3- Create a gradientDrawable Object & get the current applied Gradient drawable :
var drawable = rootConstraintLayout.background as GradientDrawable
4- Change/set the start & end colors :
drawable.colors = intArrayOf( startColor , endColor )
5- Apply the dawable to the view (here ConstraintLayout) :
rootConstraintLayout.background = drawable
if your colors are hexa so you can use this to convert them :
var startColor = Color.parseColor("#92A8F1" )
or simply use your color :
var startColor = Color.BLUE