在attrs.xml文件中配置属性

  <attr name="mainBackground" format="color"/>

在layout.xml文件中使用

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="?mainBackground" android:orientation="vertical" >    <Button  android:id="@+id/btnSet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="夜间模式" /></LinearLayout>

在styles.xml文件中

 <style name="DayTheme" parent="@android:style/Theme"> <item name="mainBackground">#ffffff</item> </style>    <!-- 夜间模式 -->    <style name="NightTheme" parent="@android:style/Theme"> <item name="mainBackground">#000000</item> </style>

在MainActivity中

public class MainActivity extends Activity implements OnClickListener {    private Button btnSet;    private boolean isnightMode = false;// 设置一个标记,表示是否为夜间模式    private String text;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        showTheme();// 显示主题操作        setContentView(R.layout.activity_main);// 重新加在布局        initView();// 初始化控件        showText();        initSetOnClickListener();// 初始化点击事件    }    private void showTheme() {        isnightMode = SharedPreferencesUtils.getBoolean(this, "night_mode",                "night_mode");        if (!isnightMode) {            setTheme(R.style.DayTheme);        } else {            setTheme(R.style.NightTheme);        }    }    private void showText() {        if (!isnightMode) {            text = "夜间模式";        } else {            text = "日间模式";        }        btnSet.setText(text);    }    private void initView() {        btnSet = (Button) findViewById(R.id.btnSet);    }    private void initSetOnClickListener() {        btnSet.setOnClickListener(this);    }    @Override    public void onClick(View v) {        if (!isnightMode) {// 表示日间模式            setTheme(R.style.NightTheme);        } else {            // 切换为日渐模式            setTheme(R.style.DayTheme);        }        isnightMode = !isnightMode;// 改变标记        // 保存        SharedPreferencesUtils.saveBoolean(this, "night_mode", "night_mode",                isnightMode);        setContentView(R.layout.activity_main);// 重新加在布局        initView();        showText();        initSetOnClickListener();    }}

说明:SharedPreferencesUtils是自己写好的工具类

更多相关文章

  1. android处理资源文件复制到database区域java
  2. android 获取视频文件第一针 作为封面
  3. Android 打开这个 apk文件
  4. Android 文件读取操作
  5. android生成R.java文件
  6. Android源码快速查找文件、搜索字符串和编译
  7. Android 快速简单实现夜间模式
  8. android中用xml文件设置button的各个状态的图片。

随机推荐

  1. Android定时刷新UI界面----Handler
  2. ReactNative前端与原生事件交互----Andro
  3. android实现播放网络视频
  4. Android(安卓)LruCache使用分析
  5. appium for windows 环境搭建
  6. Android(安卓)异步加载解决方案
  7. Android(安卓)Bitmap图像优化
  8. 轻松实现语音识别的完整代码在android开
  9. [置顶] Android(安卓)与 HttpClient 通讯
  10. android远程调试