How to programmatically change the startColor attribute of a gradient - Android

I have a form that I use in the layout. I want the color to be programmatically changed in my activity.

<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>

Is there any way to change the attributes "startColor" and "endColor" in my activity?

+3
source share
2 answers

Check this one , there is quite a bit of extra code out there, but it seems to demonstrate how to create scalable and gradient code in the code. Take a look around line 159. You may not need to create the form in XML, because you probably need to programmatically create the form, etc.

+2
source

Kotlin startColor endColor : GradientDrawable (_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"/>

View (ViewGroup), XML (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- XML (: ly_custom_header), /:

  val layoutFile = View.inflate(this, R.layout.ly_custom_header, null)

* , .

2- ViewwGroup (ConstraintLayout, LinearLayout,...), XML, , - ConstraintLayout:

   val  rootConstraintLayout= layoutFile.findViewById< ViewGroup  >(R.id.root_constraintlayout_ly_custom_header)

3- GradientDrawable Gradient Drawable:

 var drawable  = rootConstraintLayout.background as GradientDrawable

4- / :

   drawable.colors = intArrayOf(   startColor , endColor  )

5- ( ConstraintLayout):

rootConstraintLayout.background =  drawable
  • - , :

    var startColor = Color.parseColor("# 92A8F1") :

    var startColor = Color.BLUE

0

Source: https://habr.com/ru/post/1786988/


All Articles