android应用Theme(一)
16lz
2021-01-23
android切换Theme主流三种方式来切换Theme,第一种是通过内置的style来切换,一般用于夜间模式/日间模式切换。第二种是通过apk来实现插件化,第三种是通过下载zip进行解压到到相应的app文件下,应用讲需要文件读取到内存中。这篇是介绍第一种android切换Theme的方法。
首先当然是在values下面创建attrs文件,然后定义了一些attr。
<?xml version="1.0" encoding="utf-8"?>
然后再在styles文件定义两个style。
然后就是在布局文件中使用attrs。
最后就是在mainActivity设置theme并动态切换theme。
import android.os.Bundle;import android.preference.PreferenceManager;import android.annotation.SuppressLint;import android.app.Activity;import android.content.Intent;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.view.View;import android.widget.Button;public class MainActivity extends Activity {private Button mSwtichThemeBtn;private boolean isNight;private SharedPreferences sp;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);sp = PreferenceManager.getDefaultSharedPreferences(this);setTheme((isNight = sp.getBoolean("isNight", false)) ? R.style.nightTheme : R.style.dayTheme);setContentView(R.layout.activity_main);mSwtichThemeBtn = (Button) this.findViewById(R.id.swtichThemeBtn);mSwtichThemeBtn.setText(isNight?"切换日间模式":"切换夜间模式");mSwtichThemeBtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Editor edit = sp.edit();edit.putBoolean("isNight", !isNight);edit.commit();recreateForTheme();}});}@SuppressLint("NewApi")public void recreateForTheme(){if(android.os.Build.VERSION.SDK_INT >= 11){this.recreate();}else{this.finish();startActivity(new Intent(MainActivity.this,MainActivity.class));}}
更多相关文章
- android展讯平台重要的打包命令及生成镜像文件的Linux命令
- 观察者模式在android 上的最佳实践
- 从源码中浅析Android中如何利用attrs和styles定义控件
- Android开发之网络请求通信专题(二):基于HttpClient的文件上传下载
- android 自定义View类的简单使用 示例
- Android学习札记44:解读APK反编译后得到的布局文件
- Android也架构之三:简单工厂模式优化网络请求
- Android安全模式
- android文件系统及其制作