简体   繁体   中英

How do I implement dark mode in all activites?

When I click the "night mode" button it only applies in activity_main but other activities are not night mode.

Switch mSwitchNightMode = (Switch) menu.findItem(R.id.item_switch)
              .getActionView().findViewById(R.id.Switchedbtn);

      // Get state from preferences
      if (isNightModeEnabled()) {
          mSwitchNightMode.setChecked(true);
      } else {
          mSwitchNightMode.setChecked(false);
      }

      mSwitchNightMode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
              if (isNightModeEnabled()) {
                  setIsNightModeEnabled(false);
                  setAppTheme(R.style.NightMode);
              } else {
                  setIsNightModeEnabled(true);
                  setAppTheme(R.style.AppTheme);
              }

              // Recreate activity
              recreate();
          }
      });

You can't apply the selected style for your MainActivity to other Activities in this way. You should check state from the preferences while each Activity is being created and set the theme accordingly.

A suggestion could be to use one theme for your whole Application. The theme should be declared like this

<style name="MyTheme" parent="Theme.AppCompat.DayNight"> 

Then, you should add this theme inside the application tag in your AndroidManifest.xml

<application
    android:name="pkg"
    android:theme="@style/MyTheme"
/>

Finally, you can check the state from your Preferences in your Application class and apply the dark like this

   if(isNightModeEnabled()){
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
   }else{
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM