此功能是我在自己的项目中的frament里面实现的 其实很简单
一:首先我们需要加入引入appcompat v7包
compile 'com.android.support:appcompat-v7:25.1.0'
二:继承并应用DayNight主题
<style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<!--customize your theme here-->
</style>
三:新建夜间模式资源文件夹:在res
目录下新建values-night
文件夹,在此目录下新建colors.xml
文件(在夜间模式下的应用的资源)当然也可以根据需要新建drawable-night
,layout-night
等后缀为-night
的夜间资源文件夹。
values
目录下的colors.xml
的内容如下:
<?xml version="1.0" encoding="utf-8"?>
<!--values-colors.xml-->
<resources>
<color name="colorPrimary">#009688</color>
<color name="colorPrimaryDark">#00796B</color>
<color name="colorAccent">#009688</color>
<color name="textColorPrimary">#616161</color>
<color name="viewBackground">@android:color/white</color>
</resources>
四:values-night
目录下的colors.xml
的内容如下:
<!--values-night-colors.xml-->
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#35464e</color>
<color name="colorPrimaryDark">#212a2f</color>
<color name="colorAccent">#212a2f</color>
<color name="textColorPrimary">#616161</color>
<color name="viewBackground">#212a2f</color>
</resources>
五:在点击监听事件中设置当前主题模式:
int current = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; if (current == Configuration.UI_MODE_NIGHT_YES) { ((AppCompatActivity) getActivity()).getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO); } else { ((AppCompatActivity) getActivity()).getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES); }
//如果不行就在下面加入
getActivity().recreate();
好啦,就这么简单,快去试试吧,如果存在问题感谢各位能够指出来哦!