查看【日夜间模式】详情
转载必须注明本文转自严振杰的博客: http://blog.yanzhenjie.com
上图:
//第一步 改掉res—values—styles.xml 内的主题代码
<resources>
<!-- Base application theme. -->
<!--把此行代码换掉-->
<!--<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">-->
<!--换成此行代码-->
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style>
</resources>
//第二步 在AppLication类里写状态值,因为此类在整个应用中只会加载一次
public class AppLictionClass extends Application {
@Override
public void onCreate() {
super.onCreate();
Boolean b = false;
SharedPreferences sharedPreferences = getSharedPreferences("SaveBoolean", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("bbb", b);
editor.commit();
}
}
//第三步:在MainActivity里实现【那行代码】
//注意要继承AppCompatActivity 类
public class MainActivity extends AppCompatActivity {
//定义一个状态值
private Boolean bbb;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("+++++++++", "重新走了onCreate方法");
//因为系统带的这个日夜间模式,每次切换都会重走onCreate生命周期,所以会出现问题,
//为了解决这个问题,我就把状态值存到SharedPreferences 里面
SharedPreferences sharedPreferences = getSharedPreferences("SaveBoolean", MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
//从SharedPreferences里面把状态值取出来
bbb = sharedPreferences.getBoolean("bbb", false);
Log.e("+++++++++", "取到的SharedPreferences的Boolean值为:" + bbb);
//随便一个控件给点击事件触发就行
ImageView imageView = findViewById(R.id.image_night);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//拿着从SharedPreferences里取出来的值判断
if (bbb == false) {
//此行代码就是【夜间模式】】】】】】】】】】】【【【【【【【【【就是这行代码】】】】】】】】】】
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
bbb = true;
editor.putBoolean("bbb", bbb);
editor.commit();
Log.e("+++++++++", "存入的Boolean值为:" + bbb);
} else if (bbb == true) {
//此行代码就是【日间模式】】】】】】】】】】】【【【【【【【【【就是这行代码】】】】】】】】】】
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
bbb = false;
editor.putBoolean("bbb", bbb);
editor.commit();
Log.e("+++++++++", "存入的Boolean值为:" + bbb);
}
}
});
}
}
emm…确实很简单粗暴吧
TIP:
我的studio是3.1.2
支持gradle 23以上