Android dark mode adaptation, monitoring

1. The easiest way to adapt is to use ForceDark

Only apps that use a light theme can use this method. If the app uses a dark theme, Force Dark will not take effect

android:forceDarkAllowed is only available from the android 10 system. Create a values-v29 folder in all res directories, and create a styles.xml file in this folder, copy the attributes in the styles.xml that were applied before to the values- v29/styles.xml, and add at the end

<item name="android:forceDarkAllowed">true</item>

2. Specify the subject as 

parent="Theme.AppCompat.DayNight.NoActionBar"

This kind of theme will still use the light theme under normal circumstances, and will use the dark theme when switching to dark mode

If you use it like this, there are still many color details that need to be adapted again

Create values-night/colors.xml under res/ to adapt to the color in dark mode

Create drawable-night under res, place some image resources for configuring dark mode, etc.

3. Monitor system dark mode switching

Add to the corresponding <activity> in AndroidManifest.xml

android:configChanges="uiMode"

Then in Activity's onConfigurationChanged, you can monitor the dark mode switch

@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
  
  
}

/**
 * Determine whether it is dark mode
 * @param context
 * @return
 */
public static boolean isNightMode(Context context) {
    try {
        return (context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
    } catch (Exception ex) {

    }
    return false;
}

Guess you like

Origin blog.csdn.net/chongchi_wxcc/article/details/127186685
Recommended