如何以编程方式更改自定义状态按钮的颜色

时间:2014-12-30 08:42:36

标签: android

考虑How to make the corners of a button round
如何以编程方式更改背景颜色?

<?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 个答案:

答案 0 :(得分:3)

你应该这样做,

button.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFFAA0000));

答案 1 :(得分:0)

您可以按setBackgroundResource方法将背景资源设置为按钮。

假设您的按钮为bt且您的xml可绘制文件为button_bg.xml,那么您可以通过编程方式将按钮bt的背景设置为可绘制资源button_bg.xml,如下所示:

bt.setBackgroundResource(R.drawable.button_bg);

现在,只要您想设置所需布局的开始和结束颜色,请执行以下操作

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);

希望这有帮助!