我想稍微改变一个标准的Android按钮的颜色,以便更好地匹配客户端的品牌。

到目前为止,我发现最好的方法是将按钮的可绘制对象更改为位于res/drawable/red_button.xml中的可绘制对象:

<?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>

但是这样做需要为我想要自定义的每个按钮创建三个不同的绘图(一个用于静止的按钮,一个用于聚焦时的按钮,一个用于按下时的按钮)。这似乎比我需要的更复杂和非dry。

我真正想做的是对按钮应用某种颜色变换。有没有比我现在做的更简单的方法来改变按钮的颜色?


当前回答

你可以设置你的按钮的主题

<style name="AppTheme.ButtonBlue" parent="Widget.AppCompat.Button.Colored">
 <item name="colorButtonNormal">@color/HEXColor</item>
 <item name="android:textColor">@color/HEXColor</item>
</style>

其他回答

我正在使用这种方法

style.xml

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:colorPrimaryDark">#413152</item>
    <item name="android:colorPrimary">#534364</item>
    <item name="android:colorAccent">#534364</item>
    <item name="android:buttonStyle">@style/MyButtonStyle</item>
</style>

<style name="MyButtonStyle" parent="Widget.AppCompat.Button.Colored">
    <item name="android:colorButtonNormal">#534364</item>
    <item name="android:textColor">#ffffff</item>
</style>

正如你从上面看到的,我正在为我的按钮使用自定义样式。按钮颜色与强调色相对应。我发现这是一个比设置android:background更好的方法,因为我不会失去谷歌提供的涟漪效应。

现在有一个更简单的方法:androidholo -colors.com

它会让你改变所有holo drawables的颜色(按钮,旋转器,…)很容易。你选择颜色,然后下载一个压缩文件,其中包含所有分辨率的绘图。

你也可以使用这个在线工具自定义你的按钮http://angrytools.com/android/button/和使用android:background="@drawable/custom_btn"在你的布局中定义自定义按钮。

这是我的解决方案,从API 15开始完美地工作。这个解决方案保留了所有默认的按钮点击效果,如材质涟漪效应。我没有在较低的api上测试它,但它应该可以工作。

你所需要做的就是:

1)创建一个只改变颜色口音的样式:

<style name="Facebook.Button" parent="ThemeOverlay.AppCompat">
    <item name="colorAccent">@color/com_facebook_blue</item>
</style>

我推荐使用ThemeOverlay。AppCompat或你的主AppTheme作为父,以保留你的其他样式。

2)添加这两行到你的按钮小部件:

style="@style/Widget.AppCompat.Button.Colored"
android:theme="@style/Facebook.Button"

有时你的新颜色口音不会在Android Studio预览中显示,但当你在手机上启动应用程序时,颜色会发生变化。


示例按钮小部件

<Button
    android:id="@+id/sign_in_with_facebook"
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="@string/sign_in_facebook"
    android:textColor="@android:color/white"
    android:theme="@style/Facebook.Button" />

这样使用它:

buttonOBJ.getBackground().setColorFilter(Color.parseColor("#YOUR_HEX_COLOR_CODE"), PorterDuff.Mode.MULTIPLY);