看到很多APP应用上都有一个夜间模式,后来就想自己实现一个写写玩玩。下面是简单实现的一种夜间模式,不喜勿怪。
首先看下最终效果图(因为本人不会做gif图,所以….):
由于文笔能力有限就不说别的了,直接上代码了。
先增加两个style
布局xml
Activity实现
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.DayTheme);
setContentView(R.layout.activity_night_mode);
initView();
}
private void initView() {
linearLayoutList = new ArrayList<>();
llLayout = (LinearLayout) findViewById(R.id.ll_layout);
linearLayoutList.add(llLayout);
checkBoxList = new ArrayList<>();
cbMode = (CheckBox) findViewById(R.id.cb_mode);
cbMode.setOnCheckedChangeListener(this);
checkBoxList.add(cbMode);
tvView = (TextView) findViewById(R.id.tv_view);
textViewList = new ArrayList<>();
textViewList.add(tvView);
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
setTheme(R.style.NightTheme);
refreshUI();
}else {
setTheme(R.style.DayTheme);
refreshUI();
}
}
private void refreshUI() {
TypedValue background = new TypedValue();//背景色
TypedValue textColor = new TypedValue();//字体颜色
Resources.Theme theme = getTheme();
theme.resolveAttribute(R.attr.myBackground, background, true);
theme.resolveAttribute(R.attr.myTextColor, textColor, true);
for (LinearLayout layout : linearLayoutList) {
layout.setBackgroundResource(background.resourceId);
}
for (CheckBox checkBox : checkBoxList) {
checkBox.setBackgroundResource(background.resourceId);
}
for (TextView textView : textViewList){
textView.setBackgroundResource(background.resourceId);
}
Resources resources = getResources();
for (CheckBox checkBox : checkBoxList) {
checkBox.setTextColor(resources.getColor(textColor.resourceId));
}
for (TextView textView : textViewList) {
textView.setTextColor(resources.getColor(textColor.resourceId));
}
refreshStatusBar();
}
private void refreshStatusBar() {
if (Build.VERSION.SDK_INT >= 21) {
TypedValue typedValue = new TypedValue();
Resources.Theme theme = getTheme();
theme.resolveAttribute(R.attr.colorPrimary, typedValue, true);
getWindow().setStatusBarColor(getResources().getColor(typedValue.resourceId));
}
}
}
以上就是夜间模式的简单实现,有不当之处请多多指教。互相学习。