现在大多数App都支持夜间模式的切换,其实不止切换夜间还能切换别颜色选择,其实切换模式并不难,下面我们看一下这个切换的demo。相信你看完这个例子一定可以轻松的
掌握夜间模式可白天的切换了。
下面我们看一下attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="mainbackground" format="reference|color"/>
</resources>
接下来在Styles里面增加两个style
白天的风格样式
<style name="normalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="mainbackground">@color/white</item>
</style>
夜间模式的
<style name="nightTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="mainbackground">@color/night</item>
</style>
我们继续看一下布局文件,注意的是,再布局文件中 android:background="?mainbackground"这行 其实换模式就是换一个整个布局的背景,所以大家一定要注意哦
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
<-- 注意这行代码很关键->
android:background="?mainbackground"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="切换"
android:id="@+id/bt_switch"/>
</LinearLayout>
最后我们看一下MainActivity了做了那些事情
package com.example.modechanged;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
//可以供选择模式的数组
private int [] thmes={R.style.normalTheme,R.style.nightTheme};
private SharedPreferences sp;
//该标记用来判断处于那种模式下,0代表白天,1代表夜间
private int code;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//利用SharedPreferences保存模式标记
sp = getSharedPreferences("config",MODE_PRIVATE);
code = sp.getInt("code", 0);
//设置系统的主题,该方法一定要在setContentView之前调用,不然会报错
setTheme(thmes[code]);
setContentView(R.layout.activity_main);
Button bt=(Button) findViewById(R.id.bt_switch);
//点击切换主题
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(code==0){
code++;
}else if(code==1){
code--;
}
Editor edit = sp.edit();
edit.putInt("code", code);
edit.commit();
startActivity(new Intent(MainActivity.this,MainActivity.class));
finish();
}
});
}
}
就这么简单的完成了夜间模式的切换,所以模式切换没有那么难,大家看完以后是不是觉得超级简单,所以以后在遇到切换模式的需求,只需要几个步骤就可以轻松搞定了