如何将一个按钮样式应用于Android应用程序中的所有按钮?



我用基本活动创建了一个全新的应用程序。我想改变所有按钮的颜色(从默认的原色紫色到自定义的非原色绿色)。这是我的themes.xml:

<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.MyApplication" 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>
<item name="buttonStyle">@style/ButtonColour</item>
<!-- Customize your theme here. -->
</style>
<style name="Theme.MyApplication.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="ButtonColour" parent="Widget.MaterialComponents.Button">
<item name="backgroundTint">#689f38</item>
<item name="rippleColor">#c5e1a5</item>
</style>
<style name="Theme.MyApplication.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="Theme.MyApplication.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>

我在这里应用ButtonColour风格,定义在android开发文档:https://developer.android.com/guide/topics/ui/look-and-feel/themes#Widgets当应用程序使用自定义样式将按钮更改为绿色时,按钮仍然是默认的原色。

我读过其他问题(1、2和3),但他们的解决方案也没有帮助。有人能告诉我如何正确地做到这一点吗?

你必须使用materialButtonStyle而不是buttonStyle

<item name="materialButtonStyle">@style/ButtonColour</item>

变化

<style name="ButtonColour" parent="Widget.MaterialComponents.Button">

<style name="ButtonColour" parent="Theme.MyApplication">

按钮:

<Button style="@style/ButtonColour"

因为你已经使用了materialtheme作为app. Button的父主题,默认情况下会继承material主题属性。

你可以在资源的drawable文件夹中创建一个新的布局资源文件它应该是一个形状

在这个XML文件中,你可以像这样编辑你的按钮样式:'

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid
android:color="@color/antique_white"/>
</shape>

'你可以改变内部的颜色<solid。现在,你需要使用这个XML文件作为所有按钮的背景,如下所示:假设你将XML文件命名为button_style>

android:background="@drawable/button_style"

现在你可以只编辑XML文件和更改将适用于您所有的按钮。

最新更新