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

3

我通常会在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>

1
以前从未听说过Androidx中出现这样的错误,请问能否展示您的XML和JAVA代码? - Ümañg ßürmån
@Ümañgßürmån, 一个简单的布局只有一个按钮,并设置了按钮的背景为 android:background="#fff",例如,没有任何效果......我可以向你展示这个 XML,但它就是这么简单。 - Rashad.Z
但这只是一个普通的按钮(support.design),但在你提到的问题中,你说了关于Androidx的事情? - Ümañg ßürmån
@Ümañgßürmån 你说得对!但这是否意味着我不能再使用Button(支持Design)了?我有点困惑,因为它仍然可以使用。 - Rashad.Z
4个回答

4

我在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"
/>

2
您可以尝试使用:app:backgroundTint="#af2222",并删除android:background="#af2222"。这样也可以支持小于21的版本。

2
你需要为你的按钮标签添加样式,就像你正在使用Androidx与Material Design一样。
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"
  />

欢呼!

在我的XML中只有一个“Button”。IDE显示它来自android.widget.TextView。不管怎样... Material样式似乎可以工作。之前我使用了AppCompat的无边框样式,结果是白色文本在白色背景上... - The incredible Jan

0

正如svkaka的回答所提到的,我在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"似乎没有任何效果,因此这需要在材料和支持设计按钮上都进行设置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接