I have a shape that I'm using in a开发者_如何学Go 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 I could change the "startColor" and "endColor" attributes in my Activity?
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
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
精彩评论