android换主题功能,Android 切换主题风格(Theme换肤效果)

参考

截图

1、默认打开

f15dfbbd6ee2

image.png

2、点击【换主题色】

f15dfbbd6ee2

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(); //重启画面

}

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值