public class UserSettingsActivity extends BaseActivity{
private Switch nightMode;
private SharedPreferences sharedPreferences;
private static boolean night_change;
@Override
protected void onCreate(Bundle savedInstenseState) {
super.onCreate(savedInstenseState);
setContentView(R.layout.preference_layout);
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Intent intent=getIntent();
if(intent.getExtras() != null) night_change = intent.getBooleanExtra("night_change", false);
else night_change = false;
initView();
//设置状态栏
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//状态栏点击事件
myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setAction("NIGHT_SWITCH");
sendBroadcast(intent);
finish();
}
});
}
public void initView(){
nightMode=findViewById(R.id.nightMode);
nightMode.setChecked(sharedPreferences.getBoolean("nightMode",false));
nightMode.setOnCheckedChangeListener((buttonView, isChecked) -> {
setNightModePref(isChecked);
setSelfNightMode();
});
}
private void setNightModePref(boolean night){
sharedPreferences=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean("nightMode",night);
editor.commit();
}
private void setSelfNightMode(){
//重新赋值并重启本Activity
super.setNightMode();
Intent intent = new Intent(this, UserSettingsActivity.class);
intent.putExtra("night_change", !night_change); //重启一次,正负颠倒。最终为正值时重启MainActivity。
startActivity(new Intent(this, UserSettingsActivity.class));
finish();
}
@Override
public void needRefresh() {
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_BACK&&event.getAction()==KeyEvent.ACTION_DOWN){
Intent intent=new Intent();
intent.setAction("NIGHT_SWITCH");
sendBroadcast(intent);
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
UserSettingsActivity
最新推荐文章于 2022-08-17 17:05:24 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)