[英]Can't change button's background color in XML .Android studio
不要使用其他任何东西
<androidx.appcompat.widget.AppCompatButton
<!-- attributes-->
/>
而不是一个
<Button
<!--attributes-->
/>
每件事都会很好地工作。
快乐编码。
在最新的 Android Studio 版本中,Android 默认颜色为紫色。 要更改Button的颜色,您需要在 XML 中添加一行代码,即
app:backgroundTint="@color/red"
就这样!
它是紫色的,因为默认背景色调颜色。 您可以:更改 **app:backgroundTint ** instad 的android:backgroundColor 。 在这种情况下,您的 backgroundTint 将出现而不是背景颜色
或者
添加
app:backgroundTint="@null"
然后你的背景颜色就会出现。
或者
您可以更改 android manifest 中的默认主题。 例如 :
android:theme="@style/Theme.AppCompat"
或者
android:theme="@style/Theme.AppCompat.NoActionBar"
您可能正在使用targetSdkVersion
30
解决方案:将 theme.xml 样式从
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
至
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
添加属性:
app:backgroundTint="@null"
这真的很容易。 您应该在 XML 中创建一个形状。 将背景设置为该形状,然后使用该 XML 设置背景。
它与“com.google.android.material:material:1.2.0-alpha06”的更新配合得很好
或者
以编程方式执行: myButton.background = ContextCompat.getDrawable(requireContext(), R.drawable.my_background)
这两个选项,您都需要将 app:backgroundTint 属性设置为 null
应用程序:backgroundTint="@null"
检查下一个链接: https ://github.com/material-components/material-components-android/issues/889
去 res-values-themes-themes 你会发现两个主题。 一种是激活暗模式时。 去换一个暗模式。 可能发生的情况是您对暗模式有不同的风格。 我真的希望它很容易理解,因为英语不是我的第一语言
解决问题。 在 xml 中,将“android:background="@android:color/black" 中的背景替换为 backgroundTint "android:backgroundTint="@android:color/black"
我找到了解决方案。 在按钮标签内,使用
android:backgroundTint="#ccc"
将上面一行中的#ccc 替换为您喜欢的颜色的十六进制代码。 这应该解决它。
从您的按钮 xml 中删除它
android:background="@color/white"
并将其替换为
android:backgroundTint="@color/white"
直接使用hexcode改变背景
android:backgroundTint="#A9A9A9"
在按钮单击侦听器中的按钮上使用函数setBackgroundColor()
正如其他一些人提到的那样,您的主题可能会覆盖您的按钮颜色
特别是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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.