Realization of Android dark theme background and theme background color exchange


layout: post
title: Realization of Android dark theme background and theme background color swap
date: 2-12-03 21:52:38 Posted
author: 'zhangtao'
header-img: 'img/post-bg-2015.jpg'
catalog: false
tags:
-android
-android studio
-ide


Table of contents

Advantages of dark themes:

How to implement Android's dark theme mode:

Control the free switching of the dark mode in the App:

Advantages of dark themes:

1. Reduce power consumption

2. Improve visibility in the middle of the night

Dark theme available in Android 10 and above.

A dark theme can be enabled by:

  • Enable dark theme using system settings.
  • On Pixel devices, selecting Battery Saver will also enable a dark theme.

When your app runs on Android 10 (API level 29) and higher, the recommended options are different to allow users to override the system default:

  • light color
  • dark
  • system default

How to implement Android's dark theme mode:

1. Create an Empty Activity

img

2. If there is no style.xml, create a res/values/styles.xml according to this path:

img

  1. Add in style.xml to set the theme background of the application to inherit the theme background of DayNight:
<style name="AppTheme" parent="Theme.AppCompat.DayNight">

Or use MaterialComponent's dark theme:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">

4. Add in main:

<LinearLayout
		      android:layout_width="wrap_content"
		      android:layout_height="wrap_content"
		      android:forceDarkAllowed="true">
</LinearLayout>

5. Add to the theme:

<style name="AppTheme.NoActionBar">
		    <item name="android:forceDarkAllowed">true</item>
</style>

6. The final effect that can be achieved:

img

 To check which theme is currently in use, an app can run the following code:

int currentNightMode = configuration.uiMode & Configuration.UI_MODE_NIGHT_MASK;
switch (currentNightMode) {
    
    
    case Configuration.UI_MODE_NIGHT_NO:
        break;
    case Configuration.UI_MODE_NIGHT_YES:
        break;
}

Control the free switching of the dark mode in the App:

AppCompatDelegate includes these types: MODE_NIGHT_NO: Use light theme, do not use night mode MODE_NIGHT_YES: Use dark theme, use night mode MODE_NIGHT_AUTO: Automatically switch between light and dark themes according to the current time MODE_NIGHT_FOLLOW_SYSTEM (default option): Set to follow the system, usually MODE_NIGHT_NO

You can use the method setDefaultNightMode() that comes with Android Studio:

AppCompatDelegate.setDefaultNightMode()

Note: setDefaultNightMode() takes effect for the entire system.

Another method:

setLocalNightMode() can take effect on individual pages.

But can only be called by getDelegate().setLocalNightMode().
Hong Weiqi
Original link: https://blog.csdn.net/m0_58773350/article/details/128149967?spm=1001.2014.3001.5501

Guess you like

Origin blog.csdn.net/fjnu_se/article/details/128173251