博文出處: Day Night Mode,我的博客
話不多說,先上效果圖!
Twitter 實(shí)現(xiàn)夜間模式

我的實(shí)現(xiàn)

我的實(shí)現(xiàn)3
準(zhǔn)備好你的鏟鏟
- Android Support Library v7 24.2.0
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
- 新建values-night文件夾,新建colors.xml,夜間模式要設(shè)置的顏色放在這里就好了!
//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,就要另外準(zhǔn)備夜間模式的圖片在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>
一點(diǎn)解釋
- windowAnimation 在這里的作用是模擬 startActivity 的 OverridingPendingTransition, 搭配 recreate 就不會出現(xiàn)閃現(xiàn)黑屏的情況了。
- 在style 文件里為windowAnimation 創(chuàng)建一個新的style,設(shè)定漸入動畫和漸出動畫。
- AppCompatDelegate.setDefaultNightMode 是support 包里的方法,我們只要簡單設(shè)置他的mode 搭配recreate就可以變換夜間模式。
MODE_NIGHT_NO - 日間模式
MODE_NIGHT_YES - 夜間模式
MODE_NIGHT_AUTO - 根據(jù)當(dāng)前時間自動切換 亮色(light)/暗色(dark)主題
MODE_NIGHT_FOLLOW_SYSTEM(默認(rèn)選項(xiàng)). 設(shè)置為跟隨系統(tǒng),通常為 MODE_NIGHT_NO;貌似有些手機(jī)設(shè)定可以開啟夜間模式
備注
- 這個漸變效果不支持API 24 Nougat
- API 24 recreate 不會閃現(xiàn)黑屏
我把這個效果實(shí)現(xiàn)在我的項(xiàng)目里了,有興趣的童鞋可以來看一看星一星!謝謝!