无法在XML中更改按钮的背景颜色。Android Studio

25

Android studio 截图

我创建了一个TableLayout以及一些按钮。按钮的颜色被自动设置成了紫色,所以我现在无法更改它们的颜色。这是我第一次在这里。

17个回答

44

只使用这个,不要使用其他任何东西

<androidx.appcompat.widget.AppCompatButton
<!-- attributes-->
/>

而不是一个

<Button
<!--attributes-->
/>

每件事情都会很好地运作。

愉快的编码。


4
对我来说可行。但请问“按钮”存在什么问题? - Michael

26

由于默认的背景着色器颜色,它变为了紫色。 你可以: 改变**app:backgroundTint**而不是android:backgroundColor。在这种情况下,你的背景着色器将代替背景颜色。

或者

添加

app:backgroundTint="@null"

之后您的背景颜色将会显示。

或者

您可以在 Android 清单文件中更改默认主题。例如:

android:theme="@style/Theme.AppCompat"
 android:theme="@style/Theme.AppCompat.NoActionBar"

第一个对我起作用了。谢谢。 - Achilles
这正是我在寻找的,谢谢! - Ben Kigera

20

最新版的Android Studio默认颜色为紫色。 要更改按钮的颜色,您需要在XML中添加一行代码。

app:backgroundTint="@color/red"

就这些!


6
添加属性:

app:backgroundTint="@null"


5

您可能正在使用 targetSdkVersion 30

解决方案:将 theme.xml 样式更改为

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">

to

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

2

我曾经遇到同样的问题,尝试了几乎所有方法都没用!似乎是 Android Studio 4.1.1 发生了一些变化?我也不确定。

[我的解决方案] 所以我使用了 TextView 替代 Button,并设置了自定义背景,这对我有用 :/ 希望这可以帮到你!

在此输入图片描述


2
您可以像下图所示从设计编辑器中更改样式。 enter image description here

1

从您的按钮XML中删除此内容

android:background="@color/white"

并将其替换为

android:backgroundTint="@color/white"

1

正如其他人提到的那样,可能是您的主题覆盖了按钮颜色

materialButtonStyle 特别是

您可以

  • 要么将您的主题更改为 Theme.AppCompat.DayNight.NoActionBar(或类似的主题)
  • 要么覆盖 materialButtonStyle 参数
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="MyButtonStyle" parent="TextAppearance.AppCompat.Button" />
    <style name="Theme.GradientTest" parent="Theme.MaterialComponents.DayNight.DarkActionBar">

        <item name="materialButtonStyle">@style/MyButtonStyle</item>
        <!-- Other params here. -->
    </style>

1

enter image description here

您可以使用此按钮。
<androidx.appcompat.widget.AppCompatButton>

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