AndroidX在按钮上设置背景色无效

AndroidX在按钮上设置背景色无效,android,androidx,Android,Androidx,我通常使用android:background或setBackgroundColor在XML中简单地设置按钮的背景色,但现在使用AndroidX库(我假设…),这些对按钮颜色没有影响 似乎设置android:backgroundTint是可行的,但这只适用于API21及以上版本 我怎样才能做到这一点 例如: 这不应该产生一个带有红色背景按钮的布局吗 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:androi

我通常使用android:background或setBackgroundColor在XML中简单地设置按钮的背景色,但现在使用AndroidX库(我假设…),这些对按钮颜色没有影响

似乎设置android:backgroundTint是可行的,但这只适用于API21及以上版本

我怎样才能做到这一点

例如:

这不应该产生一个带有红色背景按钮的布局吗

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

您需要将样式添加到按钮标签中,就好像您在材料设计中使用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”
它应该支持,如前所述,我使用xml中的
app:backgroundTint=“#af2222”
解决了这个问题

在编程方面,我使用了以下方法:

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

else  statusButton.setBackgroundColor(MY_COLOR)

还需要注意的是,这在材料和支持设计按钮上都是必需的,因为android:background=“#fff”在这两个按钮上现在似乎都没有效果了

我在android x中使用它,而不是以前在Androidx中从未听说过这样的错误,你能展示一下你的XML和JAVA代码吗?@Ümañgßrmån一个简单的布局,只有一个按钮,并将按钮背景设置为:android:background=“#fff”例如没有效果。。。。我可以向您展示这个xml,但它就这么简单,但这是一个普通的按钮(support.design),但在您提到的关于Androidx的问题中?@mañgßrmån您的回答是正确的!。。但这是否意味着我不能再使用按钮(支持设计)?。。我很困惑,因为它可以使用
<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"
/>