0

considering How to make the corners of a button round
how to change background color programmatically ?

<?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>
Community
  • 1
  • 1

2 Answers2

3

You should do like,

button.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFFAA0000));
Mayank Patel
  • 3,868
  • 10
  • 36
  • 59
0

You can set a background resource to a button by setBackgroundResource method..

Suppose your button is bt and your xml drawable file is button_bg.xml, then you can set the background of button bt to the drawable resource button_bg.xml programmatically as shown below :

bt.setBackgroundResource(R.drawable.button_bg);

Now whenever you want to set the start and end colors of the layout you want, do the following :

View layout_bt = findViewById(R.id.layout_main);//Your layout consisting of the button bt

GradientDrawable drawable_grad = new GradientDrawable(
        GradientDrawable.Orientation.TOP_BOTTOM,
        new int[] {<start_color_here>,<end_color_here>}); //Set the start and end colors here
drawable_grad.setCornerRadius(0f);

layout_bt.setBackgroundDrawable(drawable_grad);

Hope this helps!

gsanskar
  • 673
  • 5
  • 10