1. 在res目录下的Values目录下的styles.xml里面添加:
<resources> <!--一定要将Light改DayNight--> <style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> <!--日夜间模式切换的动画--> <style name="WindowAnimationFadeInOut"> <item name="android:windowExitAnimation">@anim/fade_out</item> <item name="android:windowEnterAnimation">@anim/fade_in</item> </style> </resources>
2、res
目录下新建values-night
文件夹,文件夹名字必须是values-night
,再吧上边colors.xml复制到新创的values-night
文件夹下,并在values-night
文件夹下的colors.xml里面粘贴一下颜色
3、在主线程面写,或者在Button监听里面写;代码意思是:检测当前是夜间模式还是白天模式在res下创建anim文件夹,创建2个xml添加动画效果<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#2b2c35</color> <color name="colorPrimaryDark">#15161d</color> <color name="colorAccent">#FF4081</color> </resources>
第一个xml: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>
第二个xml:fade_out
<set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha android:duration="1000" android:fromAlpha="1.0" android:interpolator="@android:anim/decelerate_interpolator" android:toAlpha="0" /> </set>
package com.example.aaaaaaa;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = findViewById(R.id.tv);
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//日夜模式
changeDayNitht();
}
});
}
//日夜模式
private void changeDayNitht() {//更换日夜
int mode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
if(mode == Configuration.UI_MODE_NIGHT_YES) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
getWindow().setWindowAnimations(R.style.WindowAnimationFadeInOut);
} else if(mode == Configuration.UI_MODE_NIGHT_NO) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
getWindow().setWindowAnimations(R.style.WindowAnimationFadeInOut);
}
recreate();
}
}