日夜间模式的切换

   

首先日夜间模式分为三种。

    
以下展示的为第一种比较简单的方式。

   
1.在我们的styles下重新添加一套夜间模式的颜色

   

<resources xmlns:tools="http://schemas.android.com/tools">
    //这里是系统默认提供的白天模式
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:textColor">@android:color/black</item>
        <item name="mainBackground">@android:color/white</item>

    </style>
      下面就是需要我们自己添加进去的夜间模式
 <style name="NightAppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/nightColorPrimary</item>
        <item name="colorPrimaryDark">@color/nightColorPrimaryDark</item>
        <item name="colorAccent">@color/nightColorAccent</item>
        <item name="android:textColor">@android:color/white</item>
        <item name="mainBackground">@color/nightColorPrimaryDark</item>
    </style>

2.在代码中通过点击事件的监听的方法中书写下面的代码
     
     theme=(theme==R.style.AppTheme)?R.style.NightAppTheme:R.style.AppTheme;
      recreate();//这个方法主要用来重新启动Activity的生命周期

3.在最顶部创建一个int类型的字段来接受现在处于那种模式。
    比如:private int mot=R.style.Apptheme;

4.在activity中的需要书写以下两种临时保存数据的方法
       一个是存值,其中的父类给的方法需要删除掉
 @Override
    public void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
        outState.putInt("theme",theme);
    }
二一种就是取值得方法
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    theme=savedInstanceState.getInt("theme");
}
   5.在activity中的oncreate方法中书写以下代码
切记写在ContentView()这个代码之前
if(savedInstanceState!=null){
    theme=savedInstanceState.getInt("theme");
    setTheme(theme);
}
在代码中我们也可以根据theme的不同风格来判断我们索要进行的操作!



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值