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