安卓设置夜间模式和正常模式

来源:互联网 发布:python编程 pdf 编辑:程序博客网 时间:2024/06/15 20:21

修改theme:


<!--白天主题--><style name="DayTheme" parent="Theme.AppCompat.Light.DarkActionBar">    <item name="colorPrimary">@color/colorPrimary</item>    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>    <item name="colorAccent">@color/colorAccent</item>    <item name="clockBackground">@android:color/white</item>    <item name="clockTextColor">@android:color/black</item></style><!--夜间主题--><style name="NightTheme" parent="Theme.AppCompat.Light.DarkActionBar">    <item name="colorPrimary">@color/color3F3F3F</item>    <item name="colorPrimaryDark">@color/color3A3A3A</item>    <item name="colorAccent">@color/color868686</item>    <item name="clockBackground">@color/color3F3F3F</item>    <item name="clockTextColor">@color/color8A9599</item></style>

添加attr.xml文件:

<?xml version="1.0" encoding="utf-8"?><resources>        <attr name="clockBackground" format="color"/>        <attr name="clockTextColor" format="color"/></resources>

如果要改变布局中字体或者背景色,需要让该布局的设置与当前下的主题样式一致,就是在布局中添加

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"    android:layout_width="match_parent" android:layout_height="match_parent"    android:orientation="vertical"    android:background="?attr/clockBackground"    >

<Button android:layout_width="0dip" android:layout_height="wrap_content"    android:layout_weight="1"    android:id="@+id/bt_in"    android:gravity="center"    android:onClick="myClick"    android:textColor="?attr/clockTextColor"    android:text="注册" />

后面就是在java代码的处理了:
MainActivity类中:
private boolean isNight=true;
@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    supportRequestWindowFeature(Window.FEATURE_NO_TITLE);    initTheme();    setContentView(R.layout.activity_main);
}
private void initTheme() {    if (isNight) {        setTheme(R.style.NightTheme);    } else {        setTheme(R.style.DayTheme);    }}/** * 切换主题设置 */private void toggleThemeSetting() {    if (!isNight) {        setTheme(R.style.NightTheme);        isNight=true;    } else {        setTheme(R.style.DayTheme);        isNight=false;    }}
public void myClick(View v) {        switch (v.getId()) {            case R.id.bt_in:                toggleThemeSetting();                refreshUI();                break;            case R.id.bt_out:                    toggleThemeSetting();
 refreshUI();
break; } }
private void refreshUI() {    TypedValue background = new TypedValue();//背景色    TypedValue textColor = new TypedValue();//字体颜色    Resources.Theme theme = getTheme();    theme.resolveAttribute(R.attr.clockBackground, background, true);    theme.resolveAttribute(R.attr.clockTextColor, textColor, true);    ll.setBackgroundResource(background.resourceId);//将需要改变的样式进行修改
后面的就是改变样式了,根据自己喜好吧。。}






0 0
原创粉丝点击