我想要改变Android标准键的颜色,以便于适应不同客户品牌的需要。比如,为OpenTable应用添加一个"Find a Table"按钮:
目前为止,我发现的最好的方法,就是改变res/drawable/red_button.xml中有关Button的图片属性:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/red_button_pressed" /> <item android:state_focused="true" android:drawable="@drawable/red_button_focus" /> <item android:drawable="@drawable/red_button_rest" /></selector>
但这就需要我为每个按钮都创建三种不同的自定义图案,这样操作会变得异常复杂。我只是想适当的改变按钮的颜色,有什么比较简单的方法吗?
解决方案
答:emmby
(最佳答案)
我觉得,完全可以在一个文件中进行这种操作。可以将如下代码添加在custom_button.xml文件中:然后在button view中设置background="@drawable/custom_button":
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" > <shape> <gradient android:startColor="@color/yellow1" android:endColor="@color/yellow2" android:angle="270" /> <stroke android:width="3dp" android:color="@color/grey05" /> <corners android:radius="3dp" /> <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" /> </shape> </item> <item android:state_focused="true" > <shape> <gradient android:endColor="@color/orange4" android:startColor="@color/orange5" android:angle="270" /> <stroke android:width="3dp" android:color="@color/grey05" /> <corners android:radius="3dp" /> <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" /> </shape> </item> <item> <shape> <gradient android:endColor="@color/blue2" android:startColor="@color/blue25" android:angle="270" /> <stroke android:width="3dp" android:color="@color/grey05" /> <corners android:radius="3dp" /> <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" /> </shape> </item></selector>
答:Tomasz
以如下代码为例,你可以自己改写代码来设置不同的按钮颜色:
button.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFFAA0000));
答:conjugatedirection
在Tomasz方法的基础上,你也可以通过编程,使用PorterDuff中的正片叠底(multiply mod)设定整个按钮的色度,这样就可以改变按钮的颜色。如果你的标准按钮是灰色的:
button.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
这样的代码会将它设定成红色,
button.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
而这种代码会将它设为绿色,也就是说,第一个值用来设定hex格式中的颜色。