参考
截图
1、默认打开
image.png
2、点击【换主题色】
image.png
需知
主题色运用:manifest清单文件中application的属性之一,android:theme="@style/AppTheme"
在style.xml中定义不同风格的theme(对app而言的style啦)
熟悉?attr/colorPrimary等属性,在theme中定义好后,布局文件用到这些属性可以自动替换
如何点击触发后整体画面生效
代码
1、清单文件manifest中,app默认使用AppTheme(或者自定义Theme)
...
android:theme="@style/AppTheme">
...
2、style.xml 风格:
可定义app的theme,比方说AppTheme和MyTheme
一般用来定义app内各种控件样式,可重复使用,减少layout中的代码量,亦可做到后期维护换色等快速修改,不用一一修改。
用到一些自定义属性
@color/colorPrimary
@color/colorPrimaryDark
@color/colorAccent
@color/wx_bg_gray
60dp
@color/sysColorPrimary
@color/sysColorPrimaryDark
@color/sysColorAccent
80dp
@color/wx_green
@color/wx_sunset
100dp
match_parent
?attr/myButtonHeight
3、attr.xml 自定义属性(一般做自定义View的人肯定熟悉):
如果不用可忽略。这里定义后,就可在style.xml中使用这个item属性了,并可以写?attr/myBgColor 和 ?attr/myButtonHeight
4、layout.xml 布局文件使用
这里背景使用到:android:background="?attr/myBgColor"
其中一个按钮用到:style="@style/MyBtnStyle",而这个style里面属性用到?attr/myButtonHeight 。 而且这个myButtonHeight定义到了2个theme里面了!!!
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="?attr/myBgColor">
android:id="@+id/sample_text"
android:textSize="25sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
/>
android:id="@+id/et_1"
android:textSize="25sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Edit it"/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckBox"
android:checked="true"/>
android:id="@+id/btn_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击这里"/>
android:id="@+id/btn_2"
style="@style/MyBtnStyle"
android:text="换主题色"/>
5、代码控制切换主题
setTheme(),必须在setContentView(),绘画画面之前
重启当前画面:recreate()
当前画面改了,但是除了栈顶的活动画面,之后新打开画面可以是新的theme,之前在栈里存活的活动画面还是不能及时换theme,这个此处不写了,太多情况了,反正可以控制的。
//切换不同的风格,必须在setContentView之前做
if(useMyTheme){
setTheme(R.style.MyTheme);
}else{
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_main);
btn_2 = findViewById(R.id.btn_2);
btn_2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
useMyTheme = !useMyTheme;
recreate(); //重启画面
}
});