Home > Net >  Toggle method not working properly in Android Studio using JAVA
Toggle method not working properly in Android Studio using JAVA

Time:06-14

I made simple dark/light mode switcher. The application OnCreate detects the mode you are on and than changes the boolean. I'm toggling this boolean and theme with button but for some reason it changes to false after second click. It only does that when the boolean is true. On false it works fine. Here's my code:

ImageButton dark_light;
boolean isDarkMode;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dark_light = findViewById(R.id.dark_light);

    int nightModeFlags =
            getApplicationContext().getResources().getConfiguration().uiMode &
                    Configuration.UI_MODE_NIGHT_MASK;
    switch (nightModeFlags) {
        case Configuration.UI_MODE_NIGHT_YES:
            dark_light.setImageResource(R.drawable.light);
            isDarkMode = true;
            break;

        case Configuration.UI_MODE_NIGHT_NO:
            dark_light.setImageResource(R.drawable.dark);
            isDarkMode = false;
            break;
    }


    dark_light.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!isDarkMode) {
                dark_light.setImageResource(R.drawable.light);
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                isDarkMode = true;
            } else {
                dark_light.setImageResource(R.drawable.dark);
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                isDarkMode = false;
            }
            Log.d("Dark_Light", String.valueOf(isDarkMode));
        }
    });

}

CodePudding user response:

Whenever night mode is toggled, onCreate will be called again.

getApplicationContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; always gives you the initial configuration so you are always writing the same value to isDarkMode whenever the night mode is toggled.

To get the current night mode configuration, use AppCompatDelegate.getDefaultNightMode() instead

    int nightModeFlags = AppCompatDelegate.getDefaultNightMode();
    switch (nightModeFlags) {
        case AppCompatDelegate.MODE_NIGHT_YES:
            dark_light.setImageResource(R.drawable.light);
            isDarkMode = true;
            break;

        case AppCompatDelegate.MODE_NIGHT_NO:
            dark_light.setImageResource(R.drawable.dark);
            isDarkMode = false;
            break;
    }
  • Related