Android控件渲染主题颜色

需求

Android默认了几套主题颜色值,需求是能够根据用户选中主题,xml获取主题颜色或Java代码获取主题颜色,控件渲染实现换肤效果。

主题属性

声明的主题属性如下:

<!--自定义主题颜色--><style name=\\\"theme_def\\\" parent=\\\"AppTheme\\\">    <item name=\\\"bg_action_bar_def\\\">@color/bg_main_blue</item>    <item name=\\\"bg_action_bar_pressed\\\">@color/bg_main_blue_press</item>    <item name=\\\"bg_text_font\\\">@color/bg_main_text_font</item>    <item name=\\\"bg_button_end\\\">#ff1e8bfe</item>    <item name=\\\"bg_button_start\\\">#ff0d53fc</item></style>

xml获取属性值

在xml根据选中的主题颜色,使用 ?attr/bg_text_font 渲染对应属性

# code by每日教程teachcourse.cn<TextView    android:id=\\\"@+id/btn_setting\\\"    android:layout_width=\\\"wrap_content\\\"    android:layout_height=\\\"wrap_content\\\"    android:layout_alignParentRight=\\\"true\\\"    android:layout_centerVertical=\\\"true\\\"    android:text=\\\"系统设置\\\"    android:textColor=\\\"?attr/bg_text_font\\\"    android:textSize=\\\"16sp\\\"    android:visibility=\\\"visible\\\" />

编码获取属性值

在Java代码中,动态获取选中主题颜色值,封装方法 getAttColorRes()

# code by每日教程teachcourse.cnpublic static int getAttColorRes(Context context, @AttrRes int attId) {    Theme theme = context.getTheme();    TypedValue typedValue = new TypedValue();    theme.resolveAttribute(attId, typedValue, true);    int color = typedValue.data;    return color;}

代码引用

tvName.setTextColor(getAttColorRes(context,R.attr.bg_action_bar_def));

原创文章,作者:网络技术联盟站,如若转载,请注明出处:https://www.sudun.com/ask/49843.html

(0)
网络技术联盟站的头像网络技术联盟站
上一篇 2024年5月8日
下一篇 2024年5月8日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注