使用Material Design和AppCompat的Android中的着色按钮

时间:2014-10-23 01:42:19

标签: android button android-view android-button material-design

在今天AppCompat更新发布之前,我可以更改Android L中按钮的颜色,但不能更改旧版本。包含新的AppCompat更新后,我无法更改任何一个版本的颜色,当我尝试按钮时就消失了。有谁知道如何更改按钮颜色?

以下图片显示了我想要实现的目标:

picture showing desired result

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

这是我之前为改变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.DarkActionBar更改为Theme.AppCompat.Light.DarkActionBar

28 个答案:

答案 0 :(得分:215)

正式修复了支持库rev.22(2015年3月13日星期五)。查看相关的Google代码问题:

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>

答案 1 :(得分:148)

编辑(22.06.2016):

在我发布原始回复后,

Appcompat 库开始支持素材按钮。 In this post您可以看到最简单的凸起和平面按钮的实现。

原始答案:

由于AppCompat不支持该按钮,您可以使用xml作为背景。为此,我查看了Android的源代码,找到了样式材料按钮的相关文件。

1 - 从源代码中查看材料按钮的原始实现。

查看btn_default_material.xml on android source code

您可以将文件复制到项目drawable-v21文件夹中。但请勿触摸此处的颜色。您需要更改的文件是第二个文件。

<强>绘制-V21 / custom_btn.xml

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?attr/colorControlHighlight">
    <item android:drawable="@drawable/btn_default_mtrl_shape" />
</ripple>

2 - 获取原始材质按钮的形状

当你意识到这个drawable中有一个形状,你可以在this file of the source code找到它。

<inset xmlns:android="http://schemas.android.com/apk/res/android"
   android:insetLeft="@dimen/button_inset_horizontal_material"
   android:insetTop="@dimen/button_inset_vertical_material"
   android:insetRight="@dimen/button_inset_horizontal_material"
   android:insetBottom="@dimen/button_inset_vertical_material">
<shape android:shape="rectangle">
    <corners android:radius="@dimen/control_corner_material" />
    <solid android:color="?attr/colorButtonNormal" />
    <padding android:left="@dimen/button_padding_horizontal_material"
             android:top="@dimen/button_padding_vertical_material"
             android:right="@dimen/button_padding_horizontal_material"
             android:bottom="@dimen/button_padding_vertical_material" />
</shape>

3 - 获取材料按钮的尺寸

在此文件中,您可以使用文件that you can find here中的一些维度。您可以复制整个文件并将其放入文件夹中。这对于将相同尺寸(在材质按钮中使用)应用于所有按钮

非常重要

4 - 为旧版本

创建另一个可绘制文件

对于旧版本,您应该使用另一个具有相同名称的drawable。我直接将项目内联而不是引用。您可能想要引用它们。但同样,最重要的是材料按钮的原始尺寸。

<强>抽拉/ custom_btn.xml

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- pressed state -->
    <item android:state_pressed="true">
        <inset xmlns:android="http://schemas.android.com/apk/res/android"
            android:insetLeft="@dimen/button_inset_horizontal_material"
            android:insetTop="@dimen/button_inset_vertical_material"
            android:insetRight="@dimen/button_inset_horizontal_material"
            android:insetBottom="@dimen/button_inset_vertical_material">
            <shape android:shape="rectangle">
                <corners android:radius="@dimen/control_corner_material" />
                <solid android:color="@color/PRESSED_STATE_COLOR" />
                <padding android:left="@dimen/button_padding_horizontal_material"
                    android:top="@dimen/button_padding_vertical_material"
                    android:right="@dimen/button_padding_horizontal_material"
                    android:bottom="@dimen/button_padding_vertical_material" />
            </shape>
        </inset>
    </item>

    <!-- focused state -->
    <item android:state_focused="true">
        <inset xmlns:android="http://schemas.android.com/apk/res/android"
            android:insetLeft="@dimen/button_inset_horizontal_material"
            android:insetTop="@dimen/button_inset_vertical_material"
            android:insetRight="@dimen/button_inset_horizontal_material"
            android:insetBottom="@dimen/button_inset_vertical_material">
            <shape android:shape="rectangle">
                <corners android:radius="@dimen/control_corner_material" />
                <solid android:color="@color/FOCUSED_STATE_COLOR" />
                <padding android:left="@dimen/button_padding_horizontal_material"
                    android:top="@dimen/button_padding_vertical_material"
                    android:right="@dimen/button_padding_horizontal_material"
                    android:bottom="@dimen/button_padding_vertical_material" />
            </shape>
        </inset>
    </item>

    <!-- normal state -->
    <item>
        <inset xmlns:android="http://schemas.android.com/apk/res/android"
            android:insetLeft="@dimen/button_inset_horizontal_material"
            android:insetTop="@dimen/button_inset_vertical_material"
            android:insetRight="@dimen/button_inset_horizontal_material"
            android:insetBottom="@dimen/button_inset_vertical_material">
            <shape android:shape="rectangle">
                <corners android:radius="@dimen/control_corner_material" />
                <solid android:color="@color/NORMAL_STATE_COLOR" />
                <padding android:left="@dimen/button_padding_horizontal_material"
                    android:top="@dimen/button_padding_vertical_material"
                    android:right="@dimen/button_padding_horizontal_material"
                    android:bottom="@dimen/button_padding_vertical_material" />
            </shape>
        </inset>
    </item>
</selector>

结果

您的按钮会对Lollipop设备产生连锁反应。除了涟漪效应之外,旧版本将具有完全相同的按钮。但既然你为不同的状态提供了绘图,他们也会对触摸事件做出反应(就像以前那样)。

答案 2 :(得分:107)

这在AppCompat库的v23.0.0中得到了增强 增加了更多主题,包括

  

Widget.AppCompat.Button.Colored

首先,如果您还没有

,请包含appCompat依赖项
compile('com.android.support:appcompat-v7:23.0.0') {
    exclude group: 'com.google.android', module: 'support-v4'
}

既然您需要使用app compat的v23,那么您也需要定位SDK-v23!

    compileSdkVersion = 23
    targetSdkVersion = 23

values/theme

<item name="android:buttonStyle">@style/BrandButtonStyle</item>

values/style

<style name="BrandButtonStyle" parent="Widget.AppCompat.Button.Colored">
    <item name="colorButtonNormal">@color/yourButtonColor</item>
    <item name="android:textColor">@color/White</item>
</style>

values-v21/style

<style name="BrandButtonStyle" parent="Widget.AppCompat.Button.Colored">
    <item name="android:colorButtonNormal">@color/yourButtonColor</item>
    <item name="android:textColor">@color/White</item>
</style>

由于您的按钮主题基于Widget.AppCompat.Button.Colored按钮上的文字颜色默认为白色!

但是当您禁用按钮时似乎存在问题,按钮会将其颜色更改为浅灰色,但文本颜色将保持白色!

解决方法是将按钮上的文字颜色专门设置为白色! 正如我在上面所示的风格中所做的那样。

现在你可以简单地定义你的按钮,让AppCompat完成其余的工作:)

<Button
        android:layout_width="200dp"
        android:layout_height="48dp" />

残疾州 Disabled state

启用状态 Enabled State

编辑:

添加<Button android:theme="@style/BrandButtonStyle"/>

答案 3 :(得分:61)

在Android支持库22.1.0中,Google了解Button色调。 因此,另一种自定义按钮背景颜色的方法是使用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" />

答案 4 :(得分:38)

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

  

inflate - XML

AppCompat小部件:

android.support.v7.widget.AppCompatButton

AppCompat风格:

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

NB!要在xml中设置自定义颜色:请使用attr:app代替android

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

应用:backgroundTint =&#34; @颜色/ your_custom_color&#34;

示例:

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

答案 5 :(得分:25)

使用最新的支持库,您可以从AppCompatActivity继承您的活动,因此它会将您的Button充气为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中为我工作

答案 6 :(得分:16)

如果你想要低于风格

enter image description here

将此样式添加到您的按钮

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

如果你想要这种风格

enter image description here

添加以下代码

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

答案 7 :(得分:13)

答案是主题而非风格

问题是Button颜色贴在主题的colorButtonNormal上。我试图以很多不同的方式改变风格而没有运气。 所以我更改了按钮主题

使用colorButtonNormal和colorPrimary创建主题:

<style name="ThemeAwesomeButtonColor" parent="AppTheme">
    <item name="colorPrimary">@color/awesomePrimaryColor</item>
    <item name="colorButtonNormal">@color/awesomeButtonColor</item>
</style>

在按钮

中使用此主题
<Button
        android:id="@+id/btn_awesome"
        style="@style/AppTheme.Button"
        android:theme="@style/ThemeAwesomeButtonColor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn_awesome"/>

&#34; AppTheme.Button&#34;可以是任何东西扩展按钮样式就像这里我使用原色为文本颜色:

<style name="AppTheme.Button" parent="Base.Widget.AppCompat.Button">
    ...
    <item name="android:textColor">?attr/colorPrimary</item>
    ...
</style>

你得到任何你想要的与材料设计兼容的颜色的按钮。

答案 8 :(得分:4)

我刚刚创建了一个安卓库,可让您轻松修改按钮颜色和波纹颜色

https://github.com/xgc1986/RippleButton

<com.xgc1986.ripplebutton.widget.RippleButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn"
    android:text="Android button modified in layout"
    android:textColor="@android:color/white"
    app:buttonColor="@android:color/black"
    app:rippleColor="@android:color/white"/>

您不需要为每个想要不同颜色的按钮创建样式,允许您随机自定义颜色

答案 9 :(得分:4)

这项工作适用于appcompat-v7:22.2.0 in android + 4.0

你的styles.xml中的

<style name="Button.Tinted" parent="Widget.AppCompat.Button">
    <item name="colorButtonNormal">YOUR_TINT_COLOR</item>
    <item name="colorControlHighlight">@color/colorAccent</item>
    <item name="android:textColor">@android:color/white</item>
</style>
布局文件中的

<Button
    android:id="@+id/but_next"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/but_continue"
    android:theme="@style/Button.Tinted" />

答案 10 :(得分:4)

<强>布局:

<android.support.v7.widget.AppCompatButton
  style="@style/MyButton"
  ...
  />

<强> styles.xml:

<style name="MyButton" parent="Widget.AppCompat.Button.Colored">
  <item name="backgroundTint">@color/button_background_selector</item>
  <item name="android:textColor">@color/button_text_selector</item>
</style>

<强>颜色/ button_background_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="#555555"/>
    <item android:color="#00ff00"/>
</selector>

<强>颜色/ button_text_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="#888888"/>
    <item android:color="#ffffff"/>
</selector>

答案 11 :(得分:3)

如果您使用 colorButtonNormal 的样式解决方案,请不要忘记继承 Widget.AppCompat.Button.Colored ,以便涟漪效果正常工作;)< / p>

<style name="CustomButtonStyle" parent="Widget.AppCompat.Button.Colored">
      <item name="colorButtonNormal">@android:color/white</item>
</style>

答案 12 :(得分:3)

对于那些使用ImageButton的人,请按照以下方式进行操作:

在style.xml中:

<style name="BlueImageButton" parent="Base.Widget.AppCompat.ImageButton">
    <item name="colorButtonNormal">@color/primary</item>
    <item name="android:tint">@color/white</item>
</style>

在v21 / style.xml中:

<style name="BlueImageButton" parent="Widget.AppCompat.ImageButton">
    <item name="android:colorButtonNormal">@color/primary</item>
    <item name="android:tint">@color/white</item>
</style>

然后在你的布局文件中:

<android.support.v7.widget.AppCompatImageButton
    android:id="@+id/my_button"
    android:theme="@style/BlueImageButton"
    android:layout_width="42dp"
    android:layout_height="42dp"
    android:layout_gravity="center_vertical"
    android:src="@drawable/ic_check_black_24dp"
    />

答案 13 :(得分:1)

如果您只想要“平面”素材按钮,则可以使用selectableItemBackground所述的here属性自定义其背景。

答案 14 :(得分:1)

我用这个。波纹效果和按钮单击阴影效果正常。

style.xml

<style name="Button.Red" parent="Widget.AppCompat.Button.Colored">
    <item name="android:textColor">@color/material_white</item>
    <item name="android:backgroundTint">@color/red</item>
</style>

布局按钮:

<Button
        style="@style/Button.Red"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/close"/>

答案 15 :(得分:1)

另一个使用AppCompatButton的简单解决方案

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

答案 16 :(得分:1)

更新

使用设计支持库(23.2.0) appcompatwidgets ,如下所示

In Android Support Library 22.1

  

在充气布局时自动完成 - 替换Button   用AppCompatButton,TextView和AppCompatTextView等来确保   每个人都可以支持着色。在这个版本中,那些色调意识到了   窗口小部件现已公开,允许您保持着色   即使您需要子类化其中一个受支持的小部件,也支持。

色调感知小部件的完整列表:

AppCompatAutoCompleteTextView
AppCompatButton
AppCompatCheckBox
AppCompatCheckedTextView
AppCompatEditText
AppCompatMultiAutoCompleteTextView
AppCompatRadioButton
AppCompatRatingBar
AppCompatSpinner
AppCompatTextView

Material Design for Pre-Lollipop Devices

  

AppCompat(又名ActionBarCompat)最初是作为后端的   适用于在Gingerbread上运行的设备的Android 4.0 ActionBar API,   在反向移植的实现之上提供公共API层   和框架实施。 AppCompat v21提供API和   与Android 5.0同步的功能集

答案 17 :(得分:1)

将此功能拉下来的一种方法是,您只需指向一个样式而不是主题应用程序中的所有按钮都相同。
在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>

现在在您的布局中只需指向按钮中的STYLE

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

答案 18 :(得分:1)

对我来说,问题是在Android 5.0中,android:colorButtonNormal没有效果,实际上,主题中没有项目(如android:colorAccent),但在Android 4.4.3中,没有。该项目配置了compileSdkVersiontargetSdkVersion到22,所以我做了所有的更改@Muhammad Alfaifi sugessted,但最后,我注意到问题是 buildToolsVersion ,尚未更新。一旦我改为 23.0.1 ,一切都开始正常工作了。现在,android:colorButtonNormal仍然没有效果,但至少按钮会对android:colorAccent做出反应,这对我来说是可以接受的。

我希望这个提示可以帮助某人。 注意:我已经将样式直接应用于按钮,因为按钮的android:theme=[...]也没有效果。

答案 19 :(得分:0)

这个SO答案帮助我得出答案https://stackoverflow.com/a/30277424/3075340

我使用此实用程序方法设置按钮的背景色调。它适用于棒棒糖前设备:

// Set button background tint programmatically so it is compatible with pre-lollipop devices.
public static void setButtonBackgroundTintAppCompat(Button button, ColorStateList colorStateList){
    Drawable d = button.getBackground();
    if (button instanceof AppCompatButton) {
        // appcompat button replaces tint of its drawable background
        ((AppCompatButton)button).setSupportBackgroundTintList(colorStateList);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Lollipop button replaces tint of its drawable background
        // however it is not equal to d.setTintList(c)
        button.setBackgroundTintList(colorStateList);
    } else {
        // this should only happen if
        // * manually creating a Button instead of AppCompatButton
        // * LayoutInflater did not translate a Button to AppCompatButton
        d = DrawableCompat.wrap(d);
        DrawableCompat.setTintList(d, colorStateList);
        button.setBackgroundDrawable(d);
    }

}

如何在代码中使用:

Utility.setButtonBackgroundTintAppCompat(myButton,
ContextCompat.getColorStateList(mContext, R.color.your_custom_color));

这样,如果您只想更改背景色调,则不必指定ColorStateList,只需保留漂亮的按钮效果即可。

答案 20 :(得分:0)

更改单个按钮的颜色

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

答案 21 :(得分:0)

在寻找答案2天后,按钮主题在API&lt; 21。

我唯一的解决方案是覆盖AppCompatButton,不仅使用基本应用主题“colorButtonNormal”,而且还可以像这样查看backgroundTint:

public class AppCompatColorButton extends AppCompatButton {

    public AppCompatColorButton(Context context) {
        this(context, null);
    }

    public AppCompatColorButton(Context context, AttributeSet attrs) {
        this(context, attrs, android.support.v7.appcompat.R.attr.buttonStyle);
    }

    public AppCompatColorButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        if (TintManager.SHOULD_BE_USED) {
            setSupportBackgroundTintList(createButtonColorStateList(getContext(), attrs, defStyleAttr));
        }
    }

    static final int[] DISABLED_STATE_SET = new int[]{-android.R.attr.state_enabled};
    static final int[] FOCUSED_STATE_SET = new int[]{android.R.attr.state_focused};
    static final int[] PRESSED_STATE_SET = new int[]{android.R.attr.state_pressed};
    static final int[] EMPTY_STATE_SET = new int[0];

    private ColorStateList createButtonColorStateList(Context context, AttributeSet attrs, int defStyleAttr) {
        final int[][] states = new int[4][];
        final int[] colors = new int[4];
        int i = 0;

        final int themeColorButtonNormal = ThemeUtils.getThemeAttrColor(context, android.support.v7.appcompat.R.attr.colorButtonNormal);
        /*TypedArray a = context.obtainStyledAttributes(attrs, new int[] { android.R.attr.backgroundTint }, defStyleAttr, 0);
        final int colorButtonNormal = a.getColor(0, themeColorButtonNormal);*/
        TypedArray a = context.obtainStyledAttributes(attrs, android.support.v7.appcompat.R.styleable.View, defStyleAttr, 0);
        final int colorButtonNormal = a.getColor(android.support.v7.appcompat.R.styleable.View_backgroundTint, themeColorButtonNormal);
        a.recycle();
        final int colorControlHighlight = ThemeUtils.getThemeAttrColor(context, android.support.v7.appcompat.R.attr.colorControlHighlight);

        // Disabled state
        states[i] = DISABLED_STATE_SET;
        colors[i] = ThemeUtils.getDisabledThemeAttrColor(context, android.support.v7.appcompat.R.attr.colorButtonNormal);
        i++;

        states[i] = PRESSED_STATE_SET;
        colors[i] = ColorUtils.compositeColors(colorControlHighlight, colorButtonNormal);
        i++;

        states[i] = FOCUSED_STATE_SET;
        colors[i] = ColorUtils.compositeColors(colorControlHighlight, colorButtonNormal);
        i++;

        // Default enabled state
        states[i] = EMPTY_STATE_SET;
        colors[i] = colorButtonNormal;
        i++;

        return new ColorStateList(states, colors);
    }
}

然后您可以像这样定义Button颜色:

<com.example.views.AppCompatColorButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="#ffff0000"
            app:backgroundTint="#ffff0000"
            android:text="Button"
            android:textColor="@android:color/white" />

答案 22 :(得分:0)

我在按钮主题中将android:textColor设置为@null,这很有帮助。

styles.xml

<style name="Button.Base.Borderless" parent="Widget.AppCompat.Button.Borderless.Colored">
    <item name="android:textColor">@null</item>
</style>

some_layout.xml

<Button
    style="@style/Button.Base.Borderless"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hint" />

现在在colorAccent中定义的按钮文字颜色为AppTheme

<style name="AppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
    <item name="colorAccent">@color/colorAccent</item>
    <item name="borderlessButtonStyle">@style/Button.Base.Borderless</item>
    <item name="alertDialogTheme">@style/AlertDialog</item>
</style>

答案 23 :(得分:0)

我实际上并不想改变我的自定义按钮样式,但遗憾的是它们不再适用。

我的应用程序的minSdkVersion为9,之前一切正常。

我不知道为什么但是因为我删除了android:在buttonStyle之前它似乎再次起作用

now = working:

<item name="buttonStyle">@style/ButtonmyTime</item>

之前=只是灰色材质按钮:

<item name="android:buttonStyle">@style/ButtonmyTime</item>

因为我的按钮非常扁平,所以我没有新的Android版本的spezial文件夹,它们在所有Android版本中看起来都一样。

也许有人可以告诉我为什么我必须删除&#34; android:&#34; ImageButton仍在使用&#34; android:&#34;

<item name="android:imageButtonStyle">@style/ImageButtonmyTimeGreen</item>

答案 24 :(得分:0)

使用android:backgroundTint =“ @ color / customColor”,它将为按钮提供自定义颜色。就这么简单。

答案 25 :(得分:0)

如果您使用Kotlin,可以看到吗 支持MaterialButton的所有属性。不要使用android:background属性。 MaterialButton管理其自己的背景可绘制对象,并且设置新的背景意味着禁用Material按钮的颜色不再能够保证其引入的新属性将正常运行。如果更改了默认背景,则“材质按钮”不能保证定义良好的行为。 在MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        buttonClick.setOnClickListener {
            (it as MaterialButton).apply {
                backgroundTintList = ColorStateList.valueOf(Color.YELLOW)
                backgroundTintMode = PorterDuff.Mode.SRC_ATOP
            }
        }
    }
}

在activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/constraintLayout"
    tools:context=".MainActivity">
    <com.google.android.material.button.MaterialButton
        android:id="@+id/buttonNormal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Material Button Normal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <com.google.android.material.button.MaterialButton
        android:id="@+id/buttonTint"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:backgroundTint="#D3212D"
        android:text="Material Button Background Red"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonNormal" />
    <com.google.android.material.button.MaterialButton
        android:id="@+id/buttonTintMode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:backgroundTint="#D3212D"
        android:backgroundTintMode="multiply"
        android:text="Tint Red + Mode Multiply"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonTint" />
    <com.google.android.material.button.MaterialButton
        android:id="@+id/buttonClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="Click To Change Background"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonTintMode" />
</androidx.constraintlayout.widget.ConstraintLayout>

资源: Material button change color example

答案 26 :(得分:0)

如果您想通过任何颜色的代码来执行此操作,请使用以下代码:

DrawableCompat.setTintList(button.getBackground(), ColorStateList.valueOf(yourColor));

答案 27 :(得分:0)

就我而言,我没有使用 Button,而是使用 androidx.appcompat.widget.AppCompatButton 它对我有用。