Android 知识点 4.25

好记性不如破键盘

设计给了差不多是这样一张图:

屏幕快照 2017-04-25 下午11.22.16

So Easy ,一个 shape 加个 radius 就好啦,像这样:

1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#5aaae2"/>
<corners
android:radius="10dp"/>
</shape>

但是由于银行种类有十多种,颜色也不尽相同,这个时候由于我们是在 background 中直接设置 drawable 的,切换颜色的时候就会导致,圆角消失了。

除非你直接写十多个不同颜色的 shape ,那好像不大好…

所以我们要修改 solid 的中的颜色而不是 background 中的颜色。( MDZZ 一开始我老是在想怎么加个圆角的外框,这样里面的颜色修改圆角就不会消失了,还是同事提醒我的)

Google 一下, 有人是这样解决的:

屏幕快照 2017-04-25 下午11.29.08

就是说获取边框对象,创建 GradientDrawable 对象,用其 setColor() 方法动态的修改 solid 中的颜色。

好像很简单,我试了下,报错了。

和下面那哥们回复的差不多,类型转换错误,看来是 getBackground() 方法获取到的对象不一定是 GradientDrawable ,于是我添加了许多 ITEM,打了个 LOG ,getBackground().getClass().toString() ,将类型都打印了出来。

发现其中除了 GradientDrawable 还有 ColorDrawable ,再然后发现 ColorDrawable 也有动态设置 solid 颜色的方法。

那就简单了:

1
2
3
4
5
6
7
if (holder.userinfo_layout.getBackground().getClass().toString().contains("GradientDrawable")) {
GradientDrawable background1 = (GradientDrawable) holder.userinfo_layout.getBackground();
background1.setColor(color);
} else {
ColorDrawable background2 = (ColorDrawable) holder.userinfo_layout.getBackground();
background2.setColor(color);
}

简单粗暴,KO。