Android night mode switching function implementation code
Now many apps have night mode, especially reading apps. Night mode is now the standard configuration of reading apps. In fact, day mode and night mode define and apply two sets of themes of different colors to apps. Users can open them automatically or manually. Today, Android's own support package is used to realize night mode. Since the theme.appcompact.daynight theme is added to the support library in version 23.2.0, the dependent version must be higher than 23.2.0, and the minimum SDK version supported by this feature is 14. Therefore, devices compatible with Android 4.0 cannot use this feature, and devices below API level 14 will use the bright theme by default. However, there should be fewer devices below 4.0. After all, the minsdkversion of wechat is set to 14.
Add dependency
Prepare resources
Let the app inherit the daynight theme
New night mode resource folder:
Create a new values night folder in the res directory, and then create the resources of the application of the colors.xml file in the night mode in this directory. Of course, you can also create night resource folders with suffix - night such as drawable night and layout night as needed. As follows:
The contents are as follows:
values/colors.xml
values/strings.xml
values-night/colors.xml
values-night/strings.xml
Make activity inherit from appcompatactivity
Set initial theme in application
Dynamic switching
The code logic is implemented as follows:
acitivity_ main.xml
MainActivity.java
MyApplication.java
The effects are as follows:
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.