Android控件渲染主题颜色

2024-03-12 18:06 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.cn
public 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));

当前文章价值7.72元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)

你可能感兴趣的文章

来源:每日教程每日一例,深入学习实用技术教程,关注公众号TeachCourse
转载请注明出处: https://www.teachcourse.cn/3125.html ,谢谢支持!

资源分享

分类:Android 标签:
Ubuntu系统存在Python3 Ubuntu系统存在Python3
Ubuntu系统Python项目运行脚本 Ubuntu系统Python项目运行脚本
Ubuntu系统Use a production WSGI server instead Ubuntu系统Use a production W
Ubuntu系统flask服务和wsgi运行示例说明 Ubuntu系统flask服务和wsgi运行

评论已关闭!