In this tutorial, we’ll be discussing and using the Android DayNight theme in our application. If you have an app with reading materials then having night mode is helpful for ease of eyes.

在本教程中,我们将在应用程序中讨论和使用Android DayNight主题。 如果您的应用程序带有阅读材料,那么夜间模式有助于缓解视线。

Android DayNight主题 (Android DayNight Theme)

Android released a new theme: Theme.AppCompat.DayNight with the support library 23.2.0.

Android发布了一个新主题: Theme.AppCompat.DayNight和支持库23.2.0

Thanks to this theme, we can now toggle between the light and dark modes of our application. We can do so manually or let Android detect the time of the day implicitly from your phone.

由于有了这个主题,我们现在可以在应用程序的亮模式和暗模式之间切换。 我们可以手动执行操作,也可以让Android通过您的手机隐式检测一天中的时间。

This theme enhances the readability and usability of your application during the night by replacing the white flashy background with a darker one. Many reader applications have already deployed this theme in their apps.

通过用较暗的背景替换白色的闪烁背景,该主题可在夜间提高应用程序的可读性和可用性。 许多阅读器应用程序已经在其应用程序中部署了此主题。

Let’s get started with our implementation by creating a new Android Studio project with empty activity.

让我们从创建一个空活动的新Android Studio项目开始实施。

将主题添加到我们的styles.xml (Adding the theme to our styles.xml)

Let’s replace the current theme in our application with the DayNight one.

让我们用DayNight one替换应用程序中的当前主题。

<style name="AppTheme" parent="Theme.AppCompat.DayNight"><!-- Customize your theme here. --><item name="colorPrimary">@color/colorPrimary</item><item name="colorPrimaryDark">@color/colorPrimaryDark</item><item name="colorAccent">@color/colorAccent</item></style>

To set the DayNight theme in our application we use the method: AppCompatDelegate.setDefaultNightMode()

要在我们的应用程序中设置DayNight主题,我们使用以下方法: AppCompatDelegate.setDefaultNightMode()

Following are the arguments allowed in the above method.

以下是上述方法中允许的参数。

  • MODE_NIGHT_YES – Enables night mode manually.MODE_NIGHT_YES –手动启用夜间模式。
  • MODE_NIGHT_NO – Disables night mode manually.MODE_NIGHT_NO –手动禁用夜间模式。
  • MODE_NIGHT_FOLLOW_SYSTEM – Uses the system settings to determine the time of day and toggles NightMode accordingly. This is the default argument.MODE_NIGHT_FOLLOW_SYSTEM –使用系统设置确定一天中的时间,并相应地切换NightMode。 这是默认参数。
  • MODE_NIGHT_AUTO – This tries to auto-detect the time from the device location APIs. If the runtime permission for location services isn’t granted, then it uses the system time.MODE_NIGHT_AUTO –这会尝试从设备位置API自动检测时间。 如果未授予位置服务的运行时权限,则它将使用系统时间。

Add the following code in the onCreate() method.

onCreate()方法中添加以下代码。

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); //For night mode theme//AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); //For day mode themesetContentView(R.layout.activity_main);}

The theme should always be set before the setContentView method is invoked.

应该始终在调用setContentView方法之前设置主题。

什么是AppCompatDelegate? (What is AppCompatDelegate?)

An AppCompatDelegate is a class represents a delegate which you can use to extend AppCompat’s support to any Activity.
Let’s see how our activity screen looks like with the day mode and night mode enabled one by one.

AppCompatDelegate是代表委托的类,您可以使用该委托将AppCompat的支持扩展到任何Activity。
让我们看看我们的活动屏幕在白天和夜晚模式下分别启用的样子。

The TextView changes its color to white in the night mode. This is since the TextView implicitly contains the default style named : ?attr/colorPrimary which toggles the color based on the light/dark app theme. If you set a custom color @color/red on the TextView, it won’t change between day/night modes.

在夜间模式下,TextView将其颜色更改为白色。 这是因为TextView隐式包含名为的默认样式: ?attr/colorPrimary ,该样式根据明暗应用主题切换颜色。 如果在TextView上设置了自定义颜色@color/red ,则在白天/夜晚模式之间不会更改。

The Toolbar text color in the day mode is black. How to set it to white in the styles.xml itself?

白天模式下的工具栏文字颜色为黑色。 如何在styles.xml本身中将其设置为白色?

<style name="AppTheme" parent="Theme.AppCompat.DayNight"><!-- Customize your theme here. --><item name="colorPrimary">@color/colorPrimary</item><item name="colorPrimaryDark">@color/colorPrimaryDark</item><item name="colorAccent">@color/colorAccent</item><item name="android:textColorPrimary">@android:color/white</item><item name="android:textColorSecondary">@android:color/white</item></style>

To retrieve the current night mode type we use the method AppCompatDelegate.getDefaultNightMode() which returns an integer for each of the types discussed earlier, respectively.

要检索当前的夜间模式类型,我们使用AppCompatDelegate.getDefaultNightMode()方法,该方法分别为前面讨论的每种类型返回一个整数。

Having got a basic idea let’s make an application which will:

有了一个基本的想法,我们来制作一个应用程序,它将:

  • Customise resources, styles in day/night modes.在白天/夜晚模式下自定义资源,样式。
  • Toggle DayNight theme from the UI从UI切换DayNight主题
  • See how various UI widgets look in Night Mode.查看夜间模式下各种UI小部件的外观。

Android夜间模式项目结构 (Android Night Mode Project Structure)

Android DayNight主题示例代码 (Android DayNight Theme Example Code)

The code for the activity_main.xml class file is given below.

下面给出了activity_main.xml类文件的代码。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:layout_margin="@android:dimen/app_icon_size"android:text="Welcome to this tutorial."android:textColor="@color/daynight_textColor"android:textSize="18sp" /><ImageViewandroid:id="@+id/imageView"android:layout_width="250dp"android:layout_height="250dp"android:layout_centerInParent="true"android:src="@drawable/placeholder" /><TextViewandroid:id="@+id/txtNightMode"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBaseline="@+id/switchCompat"android:layout_centerHorizontal="true"android:paddingRight="8dp"android:text="Night Mode"android:textColor="@color/daynight_textColor" /><android.support.v7.widget.SwitchCompatandroid:id="@+id/switchCompat"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_marginBottom="@android:dimen/app_icon_size"android:layout_toRightOf="@+id/txtNightMode"android:checked="false"android:textAppearance="?android:attr/textAppearanceMedium" /><Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/imageView"android:layout_alignLeft="@+id/txtNightMode"android:layout_alignStart="@+id/txtNightMode"android:text="CLICK ME"android:textColor="@color/daynight_textColor" />
</RelativeLayout>
  • We’ve set a custom text color and drawable on the ImageView.我们在ImageView上设置了自定义文本颜色和可绘制的颜色。
  • To set different colors and drawables for day and night themes, we need to create separate folders for the resources.要为昼夜主题设置不同的颜色和可绘制对象,我们需要为资源创建单独的文件夹。
  • The day theme resources reside in the default directory.日主题资源位于默认目录中。
  • The night theme resources reside in folders with names appended with -night.夜间主题资源驻留在文件夹中,其名称后面带有-night
  • Hence we’ve created values-night and drawable-night folders in our project.因此,我们在项目中创建了values-nightdrawable-night文件夹。
  • The drawable filename, colors, style names must be the same in both the directories for the resources you wish to toggle in DayNight theme.您要在DayNight主题中切换的资源的两个目录中的可绘制文件名,颜色,样式名称必须相同。
  • If the above things are defined in only one of the directories, the same would be used in day and night themes.如果以上内容仅在一个目录中定义,则白天和黑夜主题中都将使用相同的内容。

The code the styles.xml in values and values-night folders are given below.

值和values-night文件夹中的styles.xml代码如下。

<resources><!-- Base application theme. --><style name="AppTheme" parent="Theme.AppCompat.DayNight"><!-- Customize your theme here. --><item name="colorPrimary">@color/colorPrimary</item><item name="colorPrimaryDark">@color/colorPrimaryDark</item><item name="colorAccent">@color/colorAccent</item><item name="android:textColorPrimary">@android:color/white</item></style><style name="MyDialog" parent="Theme.AppCompat.Light.Dialog.Alert"/><style name="MySwitch"><item name="colorControlActivated">@color/switchColor</item></style>
</resources>
<resources><!-- Base application theme. values-night.xml --><style name="AppTheme" parent="Theme.AppCompat.DayNight"><!-- Customize your theme here. --><item name="colorPrimary">@color/orange</item><item name="colorPrimaryDark">@color/orangeDark</item><item name="colorAccent">@color/colorAccent</item><item name="android:textColorPrimary">@android:color/white</item></style><style name="MyDialog" parent="Theme.AppCompat.DayNight.Dialog.Alert"/><style name="MySwitch"><item name="colorControlActivated">@color/switchColor</item></style>
</resources>

The styles defined above are used to set customise the standard DayNight theme.

上面定义的样式用于设置自定义标准DayNight主题。

The respective things for the colors.xml are defined as shown below.

如下所示定义colors.xml的各个内容。

colors.xml from values-night folder

来自values-night文件夹的colors.xml

colors.xml from values folder

来自values文件夹的colors.xml

The code for the MainActivity.java class is given below.

下面给出MainActivity.java类的代码。

package com.journaldev.daynightmode;import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);if (InitApplication.getInstance().isNightModeEnabled()) {AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);} else {AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);}setContentView(R.layout.activity_main);SwitchCompat switchCompat = findViewById(R.id.switchCompat);Button button = findViewById(R.id.button);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {new AlertDialog.Builder(MainActivity.this, R.style.MyDialog).setTitle("Title").setMessage("Message").show();}});if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES)switchCompat.setChecked(true);switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {if (isChecked) {InitApplication.getInstance().setIsNightModeEnabled(true);Intent intent = getIntent();intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);finish();startActivity(intent);} else {InitApplication.getInstance().setIsNightModeEnabled(false);Intent intent = getIntent();intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);finish();startActivity(intent);}}});}
}

In the above code we use the Switch to toggle between the day and night mode themes in our application.
We save the current mode in a SharedPreferences object.

在上面的代码中,我们使用Switch在应用程序中的白天和夜晚模式主题之间进行切换。
我们将当前模式保存在SharedPreferences对象中。

WHY?

为什么?

The theme of an activity can be set only once. Hence when the switch is toggled, we need to save the new mode in a SharedPreference object. We use the Singleton Pattern for Application class. This way the same instance of Application class can be used throughout the application.

活动的主题只能设置一次。 因此,当切换开关时,我们需要将新模式保存在SharedPreference对象中。 我们为应用程序类使用Singleton模式 。 这样,可以在整个应用程序中使用Application类的相同实例。

The code for the InitApplication.java class is given below.

下面给出了InitApplication.java类的代码。

package com.journaldev.daynightmode;import android.app.Application;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;public class InitApplication extends Application {public static final String NIGHT_MODE = "NIGHT_MODE";private boolean isNightModeEnabled = false;private static InitApplication singleton = null;public static InitApplication getInstance() {if(singleton == null){singleton = new InitApplication();}return singleton;}@Overridepublic void onCreate() {super.onCreate();singleton = this;SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);this.isNightModeEnabled = mPrefs.getBoolean(NIGHT_MODE, false);}public boolean isNightModeEnabled() {return isNightModeEnabled;}public void setIsNightModeEnabled(boolean isNightModeEnabled) {this.isNightModeEnabled = isNightModeEnabled;SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);SharedPreferences.Editor editor = mPrefs.edit();editor.putBoolean(NIGHT_MODE, isNightModeEnabled);editor.apply();}
}

It is here where we update and retrieve the night mode type from the Shared Preferences.

在这里,我们可以从“共享首选项”中更新和检索夜间模式类型。

Android夜间模式支持应用程序输出 (Android Night Mode Support App Output)

You can download the final Android DayNight Mode Project from the link below.

您可以从下面的链接下载最终的Android DayNight模式项目。

Download Android DayNight Theme Example Project下载Android DayNight主题示例项目

翻译自: https://www.journaldev.com/19352/android-daynight-theme-night-mode

应用程式中夜间模式的Android DayNight主题相关推荐

  1. android自动夜间模式吗,Android 之夜间模式(多主题)的实现思路

    引言 夜间模式其实属于多主题切换的一种,不过是最麻烦的一种.因为在夜间模式下不仅要切换主色调,次要色调等等,还要覆盖一些特殊的颜色,因为在夜间模式下总不能什么都是黑的把,那不得丑死-.-,所以当你夜间 ...

  2. iOS开发夜间模式的设置(主题切换)

    iOS开发夜间模式的设置(主题切换) 很长一段时间没有写博客了.想到自己最近刚好做了不少重构,刚好可以总结一下. 夜间模式,很多阅读类的或资讯类的App都会这个功能.以前自己也做过,现在把它抽出来封装 ...

  3. Android中夜间模式的三种实现方式

    参考:https://www.jianshu.com/p/f3aaed57fa15 在本篇文章中给出了三种实现日间/夜间模式切换的方案: 使用 setTheme 的方法让 Activity 重新设置主 ...

  4. android切换夜间模式吗,Android切换夜间模式

    1.设置主题DayNight 2.保证Activity继承AppCompatActivity 3.添加夜间模式对应的资源文件 此处最好把对应的color.drawable都设置相应的夜间资源,遇到过在 ...

  5. android 夜间模式功能,Android实现夜间模式切换功能实现代码

    现在很多App都有夜间模式,特别是阅读类的App,夜间模式现在已经是阅读类App的标配了,事实上,日间模式与夜间模式就是给App定义并应用两套不同颜色的主题,用户可以自动或者手动的开启,今天用Andr ...

  6. android自动夜间模式吗,Android夜间模式的实现方案

    原标题:Android夜间模式的实现方案 作者简介 本篇来自 Sunlight1024的投稿,详细地讲解了关于Android应用的夜间模式的实现,希望大家喜欢! Sunlight1024的博客地址: ...

  7. android 夜间模式功能,Android 夜间模式的三种实现

    实现夜间模式有很多种方式,经过多次尝试,算是找到了一种性价比较高的方式. 主题方式 这是最正统的方式,但工作量巨大,因为要全局替换 xml 布局中所有硬编码的色值,将其换成主题色.然后通过换主题达到换 ...

  8. android 夜间模式代码,Android 超简单的夜间模式如何实现?

    原标题:Android 超简单的夜间模式如何实现? 本文作者 作者: 唐子玄 实现夜间模式有很多种方式,经过多次尝试,算是找到了一种性价比较高的方式. 1 主题方式 这是最正统的方式,但工作量巨大,因 ...

  9. android 夜间模式 框架,Android 夜间模式的三种实现

    实现夜间模式有很多种方式,经过多次尝试,算是找到了一种性价比较高的方式. 主题方式 这是最正统的方式,但工作量巨大,因为要全局替换 xml 布局中所有硬编码的色值,将其换成主题色.然后通过换主题达到换 ...

最新文章

  1. apache用proxy 实现URL 转发
  2. POJ1144——网络(求割点)
  3. 【Android开发日记】第一个任务Android Service!Service靴+重力感应器+弹出窗口+保持执行...
  4. aux 参数 linux,Linux下ps aux命令中STAT的参数含义(转)
  5. 30 秒裁剪的很大一部分作用是观察什么对别人是重要的
  6. Java1009_疯狂java学习笔记1009---异常
  7. 百度竞价常用术语总结
  8. Linux下安装Java环境
  9. AIBOX-32路智能园区安全视频流分析AI服务器
  10. 从IP138上获取数据,查询多个IP的归宿地
  11. matlab编写扫雷,MATLAB版本的扫雷小游戏
  12. 【进阶版】 机器学习之主成分分析(PCA)、MDS算法、核化线性降维 (16)
  13. 为人处世,请从学会闭嘴开始!
  14. 采集网易云上面的MV保存方法
  15. 面试behavior questions 回答
  16. javascript百炼成仙 第一章 掌握JavaScript基础1.6 叶老
  17. Week8学习总结-数据库
  18. C:求一个3x3的整型矩阵对角线元素之和
  19. 西门子plc s7-200写的先进先出范例 用fifo
  20. js中的this及箭头函数

热门文章

  1. copy 和mutaleCopy
  2. Windows API-GDI入门基础知识详解(1)
  3. [转载] 利用Python构建股票交易策略 !
  4. verilog之按键消抖的理解
  5. 抽象类和接口到底是什么“垃圾“——教你分类
  6. element-UI 表单校验失效处理
  7. SQL Server实际执行计划COST欺骗案例
  8. 基于SOC方案的嵌入式开发-远程定时设备
  9. AndroidStudio 内存泄漏分析 Memory Monitor
  10. 高吞吐低延迟Java应用的垃圾回收优化