Android图片getDrawable对象渲染主题颜色

2024-03-13 15:37 Android图片getDrawable对象渲染主题颜色已关闭评论

需求

Android PDA默认提供三套主题颜色,自定义控件DzTabButton需要定义Drawable背景图,显示圆角效果,背景图颜色能够根据选中的主题颜色换肤。

DzTabButton设置背景图

DzTabButton添加背景图显示选中的效果,采用了图层叠加,下方显示如下效果:

Drawable图层叠加

Drawable图层叠加

<?xml version="1.0" encoding="utf-8"?><!-- layer-list设置图层效果:每一个item是一张图层,从下往上叠放 code by每日教程teachcourse.cn -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:left="2dp"
        android:state_checked="false">
        <shape>
            <solid android:color="@color/bg_tab_checked_color" />
            <corners android:radius="3dp" />
        </shape>
    </item>

    <item android:bottom="2dp">
        <shape>
            <solid android:color="@color/mainColor" />
            <corners
                android:bottomLeftRadius="3dp"
                android:bottomRightRadius="3dp" />
            <stroke
                android:width="4dp"
                android:color="@color/mainColor" />
        </shape>
    </item>

</layer-list>

getDrawable对象

提供了两个获取Drawable对象的方法

  1. context.getResource().getDrawable(@DrawableRes int id)
  2. context.getResource().getDrawable(@DrawableRes int id, @Nullable Theme theme)

根据当前选中的主题渲染背景图颜色,选择第二个方法,需要传入当前主题

# code by 每日教程teachcourse.cn
if (pos == 0) {
    textView.setBackground(context.getResources().getDrawable(R.drawable.bg_tab_checked_pda, context.getTheme()));
} else {
    textView.setBackground(context.getResources().getDrawable(R.drawable.bg_tab_default_pda, context.getTheme()));
}

最终呈现效果如文章开头图片所示。

不传入当前主题,提示异常

# code by 每日教程teachcourse.cn
drawable/bg_tab_checked_pda has unresolved theme attributes! 

Consider using Resources.getDrawable(int, Theme) or 

Context.getDrawable(int).java.lang.RuntimeException

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

你可能感兴趣的文章

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

资源分享

分类:Android 标签:,
genymotion注册页面打不开怎么回事 genymotion注册页面打不开怎么回
LayoutParams通知父容器childView被放置在哪里 LayoutParams通知父容器childV
Markdown一键发送工具 Markdown一键发送工具
Python常用100个关键字详细示例(1) Python常用100个关键字详细示例

评论已关闭!