androidbackgroundandroid-imagebutton

How to set an ImageButton background color to a specific color of a theme that could be adapted to the night mode?


I want to find a way to set the background color of an ImageButton to a color that I defined in my themes and which changes with day or night mode.

Is this possible?

Here is the color that I want (colorPrimary) in the themes file:

<item name="colorPrimary">@color/blue_900</item>

Thank you very much.

Bapt


Solution

  • According to Material Design guidelines (see here),

    1. In styles.xml, inherit from a DayNight theme.
        <style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight">
            ...
            ...
        </style>
    
    1. Create a new colors.xml file under the values-night directory.

    enter image description here

    enter image description here

    1. In values\colors.xml,
        <color name="primary_color">{your-light-theme-color-here}</color>
    

    In values-night\colors.xml

        <color name="primary_color">{your-dark-theme-color-here}</color>
    
    1. In styles.xml,
        <style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight">
            <item name="colorPrimary">@color/primary_color</item>
            ...
        </style>
    
    1. Set this theme in your AndroidManifest.xml
        <application
            ...
            android:theme="@style/Theme.MyApp">
        </application>
    

    I feel this is the most guideline-appropriate and efficient way.