I've 6 button in my layout. All of it were using custom xml to make it rounded corner in android:background
using single xml file. But now, how do I change the colour of every button programmatically? Since the android:background
has been used.
Asked
Active
Viewed 682 times
0

Azizi Musa
- 1,009
- 2
- 10
- 31
1 Answers
0
here is the code.
1.Create a xml file in your drawable folder like mybutton.xml and paste the following markup:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" >
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#5e7974" />
<gradient android:angle="-90" android:startColor="#345953" android:endColor="#689a92" />
</shape>
</item>
<item android:state_focused="true">
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#5e7974" />
<solid android:color="#58857e"/>
</shape>
</item>
<item >
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#5e7974" />
<gradient android:angle="-90" android:startColor="#8dbab3" android:endColor="#58857e" />
</shape>
</item>
</selector>
2.Now use this drawable for the background of your view. If the view is button then something like this:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#ffffff"
android:background="@drawable/mybutton"
android:text="Buttons" />
And for colour change use style

Sumit Pathak
- 529
- 2
- 7
- 24
-
i try using style `` but wont work. – Azizi Musa Jan 15 '16 at 07:47
-
http://stackoverflow.com/questions/12427107/how-to-set-button-selection-color-along-with-rounded-corners-in-android Try this link – Sumit Pathak Jan 15 '16 at 09:01
-
Can we programmatically change the backgroundColor of these buttons? @SummitPathak – inverted_index Jun 21 '17 at 20:53
-
1@inverted_index follow this link https://stackoverflow.com/questions/13842447/android-set-button-background-programmatically – Sumit Pathak Jun 22 '17 at 12:02
-
@SumitPathak how about corners? I want to give rounded corners to a button dynamically. The button itself is generated on the fly – inverted_index Jul 05 '17 at 09:09