考虑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>
答案 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);
希望这有帮助!