Reputation: 559
For example think we have a color resource in values/colors.xml as:
<color name="navigation_drawer_overlay">#66000000</color>
And the same color resource in values-night/colors.xml as:
<color name="navigation_drawer_overlay">#33AAAAAA</color>
By default when i fetch this color in java source codes:
ContextCompat.getColor(getContext(), R.color.navigation_drawer_overlay);
It will fetch base on automatic configuration detection.
But i want to fetch special configuration (in my case values-night version)
Is there a way to force fetch resource of my desire configuration?
Can i force fetch -night color resource?
Upvotes: 1
Views: 628
Reputation: 559
Based on answer by @user3094449
But with some modification
The correct constant for night mode is UI_MODE_NIGHT_YES, not NIGHT_MODE_YES.
private static Context getNightContext(Context fromContext) {
Configuration configuration = new Configuration(fromContext.getResources().getConfiguration());
configuration.uiMode = Configuration.UI_MODE_NIGHT_YES; // set night mode
return fromContext.createConfigurationContext(configuration);
}
Upvotes: 0
Reputation: 21
For several years later, there is a solution:
private static Context getNightContext(Context fromContext) {
Configuration configuration = new Configuration(fromContext.getResources().getConfiguration());
configuration.uiMode = UI_MODE_NIGHT_YES; // set night mode
return fromContext.createConfigurationContext(configuration);
}
// try to get the color from nightContext
Upvotes: 2
Reputation: 1571
you can try this workaround:
1) set two colors inside colors.xml like this:
<color name="navigation_drawer_overlay_day">#66000000</color>
<color name="navigation_drawer_overlay_night">#33AAAAAA</color>
2) Inside class when you need to change color do this:
switch (AppCompatDelegate.getDefaultNightMode()) {
case AppCompatDelegate.MODE_NIGHT_YES:
ContextCompat.getColor(getContext(), R.color.navigation_drawer_overlay_night);
break;
case AppCompatDelegate.MODE_NIGHT_NO:
ContextCompat.getColor(getContext(), R.color.navigation_drawer_overlay_day);
break;
}
Upvotes: 2