在今天AppCompat更新出来之前,我可以改变Android L中按钮的颜色,但在旧版本上不行。在包含新的AppCompat更新后,我无法更改两个版本的颜色,当我尝试时,按钮就消失了。有人知道怎么改变按钮的颜色吗?

下面的图片展示了我想要达到的目标:

白色按钮是默认的,红色按钮是我想要的。

这是我之前在styles.xml中改变按钮颜色所做的:

<item name="android:colorButtonNormal">insert color here</item>

要动态地进行:

button.getBackground().setColorFilter(getResources().getColor(insert color here), PorterDuff.Mode.MULTIPLY);

我也改变了@android:style/ theme . material . light的主题父元素。到Theme.AppCompat.Light.DarkActionBar


当前回答

要支持彩色按钮,请使用最新的AppCompat库(>23.2.1):

膨胀- XML

AppCompat小部件:

android.support.v7.widget.AppCompatButton

AppCompat风格:

style="@style/Widget.AppCompat.Button.Colored"

NB !在xml中设置自定义颜色:使用attr: app而不是android

(使用alt+输入或声明xmlns:app="http://schemas.android.com/apk/res-auto"使用app)

应用:backgroundTint = " @color / your_custom_color”

例子:

<android.support.v7.widget.AppCompatButton
     style="@style/Widget.AppCompat.Button.Colored"
     app:backgroundTint="@color/your_custom_color"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"     
     android:text="Colored Button"/>

或者以编程方式设置- JAVA

 ViewCompat.setBackgroundTintList(your_colored_button,
 ContextCompat.getColorStateList(getContext(),R.color.your_custom_color));

其他回答

在支持库rev.22中正式修复(2015年3月13日星期五)。参见相关谷歌代码问题:

https://issuetracker.google.com/issues/37008632

使用的例子

theme.xml:

<item name="colorButtonNormal">@color/button_color</item>

v21 / theme.xml

<item name="android:colorButtonNormal">@color/button_color</item>

更改单个按钮的颜色

ViewCompat.setBackgroundTintList(button, getResources().getColorStateList(R.color.colorId));

与最新的支持库,你可以继承你的活动从AppCompatActivity,所以它会膨胀你的按钮作为AppCompatButton,给你一个机会,风格的每一个按钮的颜色布局与使用android:theme="@style/SomeButtonStyle",其中SomeButtonStyle是:

<style name="SomeButtonStyle" parent="@android:style/Widget.Button">
    <item name="colorButtonNormal">@color/example_color</item>
</style>

我在2.3.7,4.4.1,5.0.2中工作过

在Android支持库22.1.0中,谷歌使按钮色彩感知。 另一种自定义按钮背景颜色的方法是使用backgroundTint属性。

例如,

<Button
       android:id="@+id/add_remove_button"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:backgroundTint="@color/bg_remove_btn_default"
       android:textColor="@android:color/white"
       tools:text="Remove" />

一种方法是让你只指向一个样式而不是主题,你的应用程序中的所有按钮都是一样的。 在themes.xml中添加一个主题

    <style name="Theme.MyApp.Button.Primary.Blue" parent="Widget.AppCompat.Button">
        <item name="colorButtonNormal">@color/someColor</item>
        <item name="android:textColorPrimary">@android:color/white</item>
    </style>

现在在styles.xml中添加

    <style name="MyApp.Button.Primary.Blue" parent="">
        <item name="android:theme">@style/Theme.MyApp.Button.Primary.Blue</item>
    </style>

现在在你的布局中,简单地指向按钮的样式

    <Button
        ...
        style="@style/MyApp.Button.Primary.Blue"
        ...  />