ITBOXAndroidAndroid_UI

简单实现夜间模式渐变

2016-09-13  本文已影响2942人  风丰封峰

博文出处: Day Night Mode,我的博客

话不多说,先上效果图!

Twitter 实现夜间模式 我的实现我的实现 我的实现3我的实现3

准备好你的铲铲

    <style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
//File : values/colors.xml
<resources>
    <color name="colorPrimary">@color/md_white_1000</color>
    <color name="colorPrimaryDark">@color/md_grey_600</color>
    <color name="colorAccent">@color/md_blue_500</color>
</resources>

//File : values-night/colors.xml
<resources>
    <color name="colorPrimary">#ff243447</color>
    <color name="colorPrimaryDark">#ff1b2836</color>
    <color name="colorAccent">@color/md_blue_500</color>
</resources>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportHeight="16.0"
    android:viewportWidth="16.0">
    <path
        android:fillColor="@color/colorPrimary"
        android:pathData="etc"
        android:strokeColor="#00000000"
        android:strokeWidth="1" />
</vector>

Show Me the code

//Does not work in Android Nugget
public void setDayNightMode(boolean day) {
        if (day)
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        else
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        getWindow().setWindowAnimations(R.style.WindowAnimationFadeInOut);
        recreate();
    }

//Style
    <style name="WindowAnimationFadeInOut">
        <item name="@android:windowEnterAnimation">@anim/fade_in</item>
        <item name="@android:windowExitAnimation">@anim/fade_out</item>
    </style>
    
//@anim/fade_in
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha
        android:duration="1000"
        android:fromAlpha="0"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:toAlpha="1.0" />
</set>

//@anim/fade_out
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha
        android:duration="1500"
        android:fromAlpha="1.0"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:toAlpha="0" />
</set>

一点解释

  1. windowAnimation 在这里的作用是模拟 startActivity 的 OverridingPendingTransition, 搭配 recreate 就不会出现闪现黑屏的情况了。
  2. 在style 文件里为windowAnimation 创建一个新的style,设定渐入动画和渐出动画。
  3. AppCompatDelegate.setDefaultNightMode 是support 包里的方法,我们只要简单设置他的mode 搭配recreate就可以变换夜间模式。
MODE_NIGHT_NO - 日间模式
MODE_NIGHT_YES - 夜间模式
MODE_NIGHT_AUTO - 根据当前时间自动切换 亮色(light)/暗色(dark)主题
MODE_NIGHT_FOLLOW_SYSTEM(默认选项). 设置为跟随系统,通常为 MODE_NIGHT_NO;貌似有些手机设定可以开启夜间模式

备注

我把这个效果实现在我的项目里了,有兴趣的童鞋可以来看一看星一星!谢谢!

https://github.com/chkfung/MeizhiGank

Reference

  1. https://kingideayou.github.io/2016/03/07/appcompat_23.2_day_night/
上一篇 下一篇

猜你喜欢

热点阅读