Android 切换日夜间模式
16lz
2021-01-23
在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是自己写好的工具类
更多相关文章
- android处理资源文件复制到database区域java
- android 获取视频文件第一针 作为封面
- Android 打开这个 apk文件
- Android 文件读取操作
- android生成R.java文件
- Android源码快速查找文件、搜索字符串和编译
- Android 快速简单实现夜间模式
- android中用xml文件设置button的各个状态的图片。