In my app I have one fragment where I need to use colors only from dark theme pallet.
My base AppTheme is extending from DayNight and I have colors.xml in both values and values-night folder with different hex colors for light and dark themes.
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<item name="android:windowBackground">@color/surfacePrimary</item>
<item name="colorPrimary">@color/surfacePrimary</item>
<item name="colorPrimaryDark">@color/surfacePrimary</item>
...
</style>
In this article from Chris Banes I found out that DayNight is basicaly
in values:
<style name="Theme.AppCompat.DayNight" parent="Theme.AppCompat.Light" />
and in values-night:
<style name="Theme.AppCompat.DayNight" parent="Theme.AppCompat" />
I tried to create a separate AppTheme that doesn't extend from DayNight with hope that this theme will use colors from values-night folder.
<style name="AppTheme.Dark" parent="Theme.MaterialComponents.NoActionBar">
<item name="android:windowBackground">@color/surfacePrimary</item>
<item name="colorPrimary">@color/surfacePrimary</item>
<item name="colorPrimaryDark">@color/surfacePrimary</item>
...
</style>
As you can see color attributes still points to the same colors in both themes but those colors have different hex in values/colors.xml and values-night/colors.xml. Then applied Dark theme in onCreateView of needed fragment:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
activity?.theme?.applyStyle(R.style.AppTheme_Dark, true)
return inflater.inflate(R.layout.fragment_b, container, false)
}
But this did not work out. I know that I could add separate independent colors just for this fragment and set their hex to be always equal to one in dark mode. But I would really like to avoid it and use already existing colors I have.
How can I force AppTheme.Dark to use colors from values-night/colors.xml?