需求
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元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)
评论已关闭!