Android开发小技巧1 ——动态设置shape和Background drawable

UI妹子每次都会找我们给图像和文本加圆角矩形,更换背景颜色

这个时候大家的做法一般都是加静态shape(如下所示)

这里写图片描述

具体代码如下所示:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid
        android:color="#fff0f0f0" />
    <size
        android:width="31dp"
        android:height="16dp" />
</shape>

要是一个两个还好,但是要求越来越多的话,xml就会越来越多,如果你的命名再没有讲究就会出现即使你写过一个背景xml但是忘叫啥了,找都不找不到的尴尬情况,这个时候动态设置shape就呼之欲出了,使用也很简单

GradientDrawable gd = new GradientDrawable();
gd.setColor(Color.parseColor("#00ff00"));
gd.setCornerRadius(8f);
gd.setStroke(2, Color.parseColor("#ff0000"));//描边的颜色和宽度
gd.setGradientType(GradientDrawable.RECTANGLE);
mTvTeam.setBackground(gd);

猜你喜欢

转载自blog.csdn.net/losingcarryjie/article/details/80847900