话不多说,先上效果图!
Twitter 实现夜间模式
我的实现
准备好你的铲铲
- Android Support Library v7 24.2.0
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
-
新建values-night文件夹,新建colors.xml,夜间模式要设置的颜色放在这里就好了!
//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>
-
Svg 的 fillcolor 取用你的color.xml 就好了!方便!如果不是svg,就要另外准备夜间模式的图片在drawable-night 文件夹里
<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>
一点解释
- windowAnimation 在这里的作用是模拟 startActivity 的 OverridingPendingTransition, 搭配 recreate 就不会出现闪现黑屏的情况了。
- 在style 文件里为windowAnimation 创建一个新的style,设定渐入动画和渐出动画。
- AppCompatDelegate.setDefaultNightMode 是support 包里的方法,我们只要简单设置他的mode 搭配recreate就可以变换夜间模式。
MODE_NIGHT_NO - 日间模式 MODE_NIGHT_YES - 夜间模式 MODE_NIGHT_AUTO - 根据当前时间自动切换 亮色(light)/暗色(dark)主题 MODE_NIGHT_FOLLOW_SYSTEM(默认选项). 设置为跟随系统,通常为 MODE_NIGHT_NO;貌似有些手机设定可以开启夜间模式
备注
- 这个渐变效果不支持API 24 Nougat
- API 24 recreate 不会闪现黑屏
我把这个效果实现在我的项目里了,有兴趣的童鞋可以来看一看星一星!谢谢!
https://github.com/chkfung/MeizhiGank
Reference
- https://kingideayou.github.io/2016/03/07/appcompat_23.2_day_night/
来自:http://www.jianshu.com/p/f30ebec8b4ed