AndroidX 在按钮上设置背景颜色没有效果

AndroidX Setting Background Color on Button has NO Effect

我通常只是在 XML 中使用 android:background 或以编程方式使用 setBackgroundColor 设置按钮的背景颜色,但现在使用 AndroidX 库(我假设...),这些对按钮颜色

设置 android:backgroundTint 似乎有效,但这仅适用于 API 21 及更高版本

我怎样才能做到这一点?

示例:

这是否会生成带有红色背景按钮的布局...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:background="#af2222"/>

</LinearLayout>

您需要将样式添加到您的按钮标签,就像您使用具有 material 设计的 Androidx 一样。

style="@style/Widget.MaterialComponents.Button"

此样式可让您将 primaryColor 设置为背景色。

因此您的整个代码将如下所示:

<android.support.design.button.MaterialButton
   style="@style/Widget.MaterialComponents.Button"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Messages"
   android:minWidth="200dp"
   app:cornerRadius=”16dp”
   app:icon="@drawable/ic_action_setting" 
   app:cornerRadius="@dimen/_16sdp"
   app:backgroundTint="@color/colorAccent"
   app:iconTint="@color/light_pitch" 
   app:iconPadding="-12dp"
  />

干杯!

您可以尝试使用:app:backgroundTint="#af2222" 并删除 android:background="#af2222" 它应该也支持 <21

正如提到的,我在xml中使用了app:backgroundTint="#af2222"来解决这个问题。

以编程方式,我使用了这个:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) statusButton.backgroundTintList = ColorStateList.valueOf(MY_COLOR)

else  statusButton.setBackgroundColor(MY_COLOR)

另请注意,这在 material 和支持设计按钮上都是必需的,因为 android:background="#fff" 现在似乎都没有效果

我在 android x 中使用这个而不是 <Button 并且背景颜色会改变

<androidx.appcompat.widget.AppCompatButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:background="@color/colorAccent"
        android:text="Done"
/>