Android默认按钮颜色

时间:2020-10-17 08:22:34

标签: java android xml android-button material-components-android

当我打开一个新的android studio项目时,按钮的默认颜色为紫色。我希望默认颜色是灰色的默认按钮颜色(我想您知道我的意思)。我试图通过xml和java更改颜色,但没有任何效果。我希望默认按钮颜色为灰色,而不必每次都更改。 enter image description here

enter image description here

themse.xml:

<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.HangmanGame" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    <!-- Primary brand color. -->
    <item name="colorPrimary">@color/purple_500</item>
    <item name="colorPrimaryVariant">@color/purple_700</item>
    <item name="colorOnPrimary">@color/white</item>
    <!-- Secondary brand color. -->
    <item name="colorSecondary">@color/teal_200</item>
    <item name="colorSecondaryVariant">@color/teal_700</item>
    <item name="colorOnSecondary">@color/black</item>
    <!-- Status bar color. -->
    <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
    <!-- Customize your theme here. -->
</style>

themes.xml(晚上)

<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.HangmanGame" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    <!-- Primary brand color. -->
    <item name="colorPrimary">@color/purple_200</item>
    <item name="colorPrimaryVariant">@color/purple_700</item>
    <item name="colorOnPrimary">@color/black</item>
    <!-- Secondary brand color. -->
    <item name="colorSecondary">@color/teal_200</item>
    <item name="colorSecondaryVariant">@color/teal_200</item>
    <item name="colorOnSecondary">@color/black</item>
    <!-- Status bar color. -->
    <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
    <!-- Customize your theme here. -->
</style>

2 个答案:

答案 0 :(得分:5)

由于您使用的是 Theme.MaterialComponents.* 主题,因此Button(由MaterialButton代替)的默认背景色为 { {1}} 在您的应用主题中定义。
就您而言:

colorPrimary

您可以更改此值(但这会影响所有小部件)。

如果要全局更改应用程序中的按钮样式,还可以在应用程序主题中添加<item name="colorPrimary">@color/purple_500</item> 属性:

materialButtonStyle

具有:

<style name="Theme.HangmanGame" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
   <item name="materialButtonStyle">@style/Widget.App.Button</item>
</style>

如果只想在按钮中更改此颜色,则还可以使用<style name="Widget.App.Button" parent="Widget.MaterialComponents.Button"> <item name="backgroundTint">@color/...</item> </style> 属性删除app:backgroundTint属性:

android:background

如果您想通过<Button app:backgroundTint="@color/..."/> 属性使用自定义背景,则必须添加android:background以避免按钮被着色。

答案 1 :(得分:0)

我认为最简单的方法是进入三个 xml 文件:src\main\res\values\colors.xml、src\main\res\values\themes.xml 和 src\main\res\values-night \themes.xml

在colors.xml 中,添加一种颜色并将其命名为“按钮”,然后将颜色设置为您想要的颜色。有关颜色代码的简单列表,请参阅此答案:https://stackoverflow.com/a/7323234/5374362

该行看起来像这样:

<color name="button">#808080</color>  //That code is the gray you want.

在两个主题文件中,将colorPrimary改为“@color/button”

这将影响应用中的每个按钮。