0

Here is the code for the detect dark/light theme when we using the application.

public void onConfigurationChanged(@NonNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    int mSysThemeConfig = newConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK;
    layout = findViewById(R.id.mainLayout);
    switch (mSysThemeConfig) {
        //Light theme
        case Configuration.UI_MODE_NIGHT_NO:
            layout.setBackgroundResource(R.drawable.lightTheme);
            layout.setLayoutParams(new RelativeLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            break;
        //Dark theme
        case Configuration.UI_MODE_NIGHT_YES:
            layout.setBackgroundResource(R.drawable.darkMode);
            layout.setLayoutParams(new RelativeLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            break;
    }
}

How do I detect the dark/light theme when we start an application?

S4amon
  • 43
  • 7

1 Answers1

1

I just found it

Maybe this can help you

int nightModeFlags =
getContext().getResources().getConfiguration().uiMode &
Configuration.UI_MODE_NIGHT_MASK;
switch (nightModeFlags) {
case Configuration.UI_MODE_NIGHT_YES:
     doStuff();
     break;

case Configuration.UI_MODE_NIGHT_NO:
     doStuff();
     break;

case Configuration.UI_MODE_NIGHT_UNDEFINED:
     doStuff();
     break;
}

OR you can go in this link

Android - How to detect if night mode is on when using AppCompatDelegate.MODE_NIGHT_AUTO

Cyrille Con Morales
  • 918
  • 1
  • 6
  • 21
  • thank you it is exactly what I want! Also, please remember to bind the view if you would like to change the attribute of the layout `layout = findViewById(R.id.mainLayout);` . If cannot resolve method`getContext()`, change it to youractivity.this.get..... – S4amon Jan 27 '21 at 04:13