Issue
TL,DR;
ContextCompat.getColor()
does not use the night colors (values-night/colors.xml
) though it should when night mode is enabled.
Here is the problem:
Hi everyone,
So I'm implementing a dark theme for my Android app, I call this to enable it :
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
I have set colors in values/colors.xml
and there dark version in values-night/colors.xml
. The colors changes well depending on the nightMode, BUT :
when I use ContextCompat.getColor(getApplicationContext(), R.id.myColor)
, it uses the normal colors (values/colors.xml
) and not the night colors (values-night/colors.xml
).
In my build.gradle
, I have set these :
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0-beta01'
Could someone please tell me what am I doing wrong ?
PS : I already looked at the following question and it does not answer this problem https://stackoverflow.com/questions/57779661/contextcompat-getcolor-method-ignores-night-mode
Solution
I faced similar issues with night mode. Some screens were fine but others were keeping the regular theme. In the end, I found out that I was instantiating some views using the Application's context instead of the current's activity context. For some reason, Application's context does not track this kind of information.
So, update your code to use current's activity context instead of the application context.
For reference for other users. Avoid:
ContextCompat.getColor(getApplicationContext(), R.id.myColor)
And use:
// In a Activity
ContextCompat.getColor(this, R.id.myColor)
// In a View
ContextCompat.getColor(getContext(), R.id.myColor)
// In a Fragment (check against null because getContext can trigger a NPE
Context context = getContext()
if (context != null) {
ContextCompat.getColor(context, R.id.myColor)
}
Answered By - W0rmH0le
Answer Checked By - David Marino (JavaFixing Volunteer)