We know that in android application we can change background color of checkboxes by using SetButtonDrawable and a xml file.
This xml file can be define with gradients or a simple file that used images in drawables.
This article show a sample with Gradients: Android: Set color of CheckBox
And also this is another sample that i used:
<item android:state_checked="true">
<layer-list>
<item>
<shape android:shape="rectangle">
<solid android:color="#9b9b9b" />
<corners android:radius="5dp" />
</shape>
</item>
<item android:top="2dp" android:left="1.5dp" >
<shape android:shape="rectangle">
<solid android:color="#ffffff" />
<corners android:radius="5dp" />
<size android:height="20dp" android:width="20dp" />
</shape>
</item>
<item android:top="2dp" android:bottom="1dp" android:left="1.5dp">
<shape android:shape="rectangle">
<gradient android:startColor="#ff7dbce9" android:endColor="#ff2578b3" android:angle="270" />
<corners android:radius="5dp" />
<size android:height="20dp" android:width="20dp" />
</shape>
</item>
<item android:top="2dp" android:bottom="1dp" android:left="1.5dp">
<shape android:shape="rectangle">
<gradient android:startColor="#ff7dbce9" android:endColor="#ff2578b3" android:angle="270" />
<corners android:radius="5dp" />
<size android:height="20dp" android:width="20dp" />
</shape>
</item>
<item>
<bitmap android:gravity="center" android:src="@drawable/tick_red_icon"/>
</item>
</layer-list>
</item>
<item >
<layer-list>
<item>
<shape android:shape="rectangle">
<solid android:color="#9b9b9b" />
<corners android:radius="5dp" />
</shape>
</item>
<item android:top="2dp" android:left="1.5dp" >
<shape android:shape="rectangle">
<solid android:color="#ffffff" />
<corners android:radius="5dp" />
<size android:height="20dp" android:width="20dp" />
</shape>
</item>
<item android:top="2dp" android:bottom="2dp" android:left="1.5dp">
<shape android:shape="rectangle">
<solid android:color="#e5e4e4" />
<corners android:radius="5dp" />
<size android:height="20dp" android:width="20dp" />
</shape>
</item>
</layer-list>
</item>
Also we know that if we wanna change the gradient colors we need to define it as a DrawableGradient in runtime and then use this.
The question is this: How can we define some comlex gradients like above as DrawableGradient to have the ability that change them color on runtime?
Or if there is a bad solution is there any better solution that we set the background color of checkboxes and can changes their color on runtime?
Finally by research I found this article and based on this I developed a code that is this question’s answer.
We have to define each layer in a separate xml file like this:
and then by retrieving them on run-time we can change their items.(Layer is the name of my xml file)
Now, by using
StateListDrawablewe can define witch state is related to witch layer:Now, you can join changing this xml in runtime 🙂