How to programatically change the startColor attribute of gradient - Android

前端 未结 2 763
逝去的感伤
逝去的感伤 2020-12-21 07:11

I have a shape that I\'m using in a layout. I want the color to be programmatically changed in my activity.



        
相关标签:
2条回答
  • 2020-12-21 07:20

    Check this out, there's quite a bit of additional code but it seems to demonstrate how to create a drawable and gradient drawable in code... look around line 159. You may not need to create the shape in XML as you will probably need to progmatically create the shape etc

    0 讨论(0)
  • 2020-12-21 07:33

    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

    0 讨论(0)
提交回复
热议问题