博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
应用程式中夜间模式的Android DayNight主题
阅读量:2533 次
发布时间:2019-05-11

本文共 10347 字,大约阅读时间需要 34 分钟。

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替换应用程序中的当前主题。

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()方法中添加以下代码。

@Override    protected 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 theme        setContentView(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.

android day mode

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本身中将其设置为白色?

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类文件的代码。

  • 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代码如下。

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的各个内容。

android daynight colors night mode

colors.xml from values-night folder

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

android daynight colors day mode

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 {    @Override    protected 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() {            @Override            public 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() {            @Override            public 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 object.

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

我们将当前模式保存在对象中。

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 for Application class. This way the same instance of Application class can be used throughout the application.

活动的主题只能设置一次。 因此,当切换开关时,我们需要将新模式保存在SharedPreference对象中。 我们为应用程序类使用 。 这样,可以在整个应用程序中使用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;    }    @Override    public 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模式项目。

翻译自:

转载地址:http://foqzd.baihongyu.com/

你可能感兴趣的文章
Azure云服务托管恶意软件
查看>>
My安卓知识6--关于把项目从androidstudio工程转成eclipse工程并导成jar包
查看>>
旧的起点(开园说明)
查看>>
生产订单“生产线别”带入生产入库单
查看>>
crontab导致磁盘空间满问题的解决
查看>>
java基础 第十一章(多态、抽象类、接口、包装类、String)
查看>>
Hadoop 服务器配置的副本数量 管不了客户端
查看>>
欧建新之死
查看>>
自定义滚动条
查看>>
APP开发手记01(app与web的困惑)
查看>>
笛卡尔遗传规划Cartesian Genetic Programming (CGP)简单理解(1)
查看>>
mysql 日期时间运算函数(转)
查看>>
初识前端作业1
查看>>
ffmpeg格式转换命令
查看>>
万方数据知识平台 TFHpple +Xpath解析
查看>>
Hive实现oracle的Minus函数
查看>>
秒杀多线程第四篇 一个经典的多线程同步问题
查看>>
RocketMQ配置
查看>>
vs code调试console程序报错--preLaunchTask“build”
查看>>
蚂蚁金服井贤栋:用技术联手金融机构,形成服务小微的生态合力
查看>>