1.修改项目中styles文件
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
2.使用夜间模式的设置代码,代码如下(项目)
工具包新建:
SharedPreferencesUtil
public class SharedPreferencesUtil {
private static SharedPreferences.Editor editor;
//添加ui模式
public static void addModeUI(Context context, boolean bool) {
editor = context.getSharedPreferences("mode", Context.MODE_PRIVATE).edit();
editor.putBoolean("mode_ui", bool);
editor.commit();
}
/**
* * 是否是夜间模式
* <p>
* * @param context
* <p>
* * @return
* <p>
*
*/
public static int getNight(Context context) {
boolean bool = context.getSharedPreferences("mode", Context.MODE_PRIVATE).getBoolean("mode_ui", false);
return bool ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO;
}
}
UIModeUtil
public class UIModeUtil {
/**
* * 夜间模式切换
* <p>
*
*/
public static void changeModeUI(AppCompatActivity activity) {
int currentNightMode = activity.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
if (currentNightMode == Configuration.UI_MODE_NIGHT_NO) {
activity.getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
SharedPreferencesUtil.addModeUI(activity.getBaseContext(), true);
} else {
activity.getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
SharedPreferencesUtil.addModeUI(activity.getBaseContext(), false);
}
}
/**
* * 显示当前的模式
* <p>
* * @param activity
* <p>
* * @param mode
* <p>
*
*/
public static void showModeUI(AppCompatActivity activity, int mode) {
activity.getDelegate().setLocalNightMode(mode);
}
}
MainActivity主页面
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button sc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
sc = (Button) findViewById(R.id.sc);
sc.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sc:
Intent intent = new Intent(this,SetActivity.class);
startActivity(intent);
break;
}
}
//每次执行该方法检查是否设置夜间模式
@Override
protected void onStart() {
super.onStart();
int mode = SharedPreferencesUtil.getNight(this);
UIModeUtil.showModeUI(this, mode);
}
}
SetActivity设置页面
public class SetActivity extends AppCompatActivity {
private AppCompatActivity activity;
private CheckBox checkBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set);
initView();
activity = this;
}
private void initView() {
checkBox = (CheckBox) findViewById(R.id.cb);
int mode = SharedPreferencesUtil.getNight(this);
if (mode == AppCompatDelegate.MODE_NIGHT_YES) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
UIModeUtil.changeModeUI(activity);
recreate();
}
});
}
}
网友评论