Home > Enterprise >  How to nest button style element within app theme in Android Studio project
How to nest button style element within app theme in Android Studio project

Time:11-07

I am trying to define the Material Button background colour as a theme in my Android App, so that all buttons get the style from the app theme. I have the following style defined in my Android app.

I have the following in my theme/style xml file

<style name="Theme.SimpleTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    <!-- Some theming -->
</style>

<style name="SimpleButton" parent="Widget.MaterialComponents.Button">
    <item name="colorPrimary">@color/blue_grey_800</item>
    <item name="colorOnPrimary">@color/white</item>
</style>

Then in the layout file, I have:

<com.google.android.material.button.MaterialButton
    android:theme="@style/SimpleButton" />

Now, this works to get a particular button have my desired background colour, but I have to set the Style attribute in all the material button elements in all the layout files.

Is there any way I can nest the styles so that I do not need to explicitly mention the style in all the buttons?

CodePudding user response:

Yes, there is a way to do that.

First, create a theme for your button, and make it inherit AppCompat Button (although it's a material button). for example:

<style name="bTheme" parent="Widget.AppCompat.Button">
        <item name="android:backgroundTint">@color/black</item>
        <item name="android:textColor">@color/white</item>
</style>

Then, on the main app's theme, add the following line:

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

This should do the trick :)

  • Related