Separate day/night selector for button text color

Viewed 302

I created a custom selector for button text color:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="?android:attr/textColorPrimary" android:state_enabled="true" />
    <item android:alpha="0.38" android:color="?android:attr/textColorPrimary" />
</selector>

However, I would like to use ?android:attr/textColorPrimary for the color in night theme and ?android:attr/colorPrimary in day theme. How can I achieve this?

2 Answers

create folder drawable-night at put night-variant in it (same file name), leave untouched file in common drawable folder. this way you can also "overwrite" attributes like colors, dimens, even layout

best option would be to introduce DayNight theme support, check out official doc, plenty of tutorials in search engines... (look for DayNight theming)

Each attribute will have its complementary light and dark color in a day/night mode setting. You can create a new item in the theme.xml for light mode and dark mode and use that.

Inside res directory create a values-night folder and inside that create a themes.xml this will contain your night theme. The themes.xml in values folder contains your day theme.

For example Say: this is your theme.xml in values folder

<resources xmlns:tools="http://schemas.android.com/tools">

<style name="Theme.MyApp" parent="Base.Theme.MyApp">

    <item name="buttonColor">@color/light_base_1</item>

</resources>

This is your theme.xml in values-night folder

    <resources xmlns:tools="http://schemas.android.com/tools">

<style name="Theme.MyApp" parent="Base.Theme.MyApp">

    <item name="buttonColor">@color/dark_base_1</item>

</resources>

create an attribute in attrs.xml file

    <attr name="buttonColor" format="color" />

Then you can use this new attribute in the selector

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="?android:attr/textColorPrimary" android:state_enabled="true" />
<item android:alpha="0.38" android:color="?attr/buttonColor" />
Related