[英]How do you apply a button style to all buttons in an Android app?
我使用基本活動創建了一個全新的應用程序。 我想更改所有按鈕的顏色(從默認的紫色原色到自定義的非原色綠色)。 這是我的主題.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 當應用程序以該自定義樣式運行時要將按鈕更改為綠色,按鈕仍然是默認的原色。
您必須使用 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 作為應用程序的父主題。 按鈕,默認繼承材質主題屬性。
您可以在資源的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 文件,更改將應用於您的所有按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.