GradientDrawable 的静态使用和动态用法

本文详细介绍了在Android开发中GradientDrawable的两种使用方式:静态XML定义和动态代码设置。包括shape属性设置、边角圆润、颜色填充等,并提供了一个ShapeBuilder类的示例,用于简化形状背景的创建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、GradientDrawable 的静态使用

项目中我们常用的是GradientDrawable 的静态使用即在xml中使用shape标签定义,这也是我们常用的

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <corners android:radius="3dp"></corners>
    <gradient
        android:centerColor="@color/color_ffffff"
        android:endColor="@color/color_ffffff"
        android:startColor="@color/color_ffffff"></gradient>
    <solid android:color="@color/color_3699ff"></solid>
    <stroke
        android:width=""
        android:dashWidth=""></stroke>
    <padding
        android:bottom=""
        android:left=""></padding>
    <size android:width=""></size>
</shape>

2、GradientDrawable 的动态用法,为了防止过多的创建xml还可以在代码中设置shape背景

1、基本属性设置

GradientDrawable bg = new GradientDrawable();
        bg.setShape(shape);
        bg.setStroke(lineWidth,lineColor,dashWidth,dashGap);
        bg.setCornerRadius(cornerRadius);
        bg.setColor(bkColor);
mTextView.setBackground(bg);

其中shepe属性有LINE 、OVAL、RECTANGLE、RING和xml的属性相对应。

2、除此之外我们还可以对其进项封装来方便使用

public class ShapeBuilder {
    public Drawable build() {
        final GradientDrawable bg = new GradientDrawable();
        bg.setShape(shape);
        bg.setStroke(lineWidth,lineColor,dashWidth,dashGap);
        bg.setCornerRadius(cornerRadius);
        bg.setColor(bkColor);
        return bg;
    }

    public ShapeBuilder shape(int shape) {
        this.shape = shape;
        return this;
    }
    
    public ShapeBuilder line(int width,String color) {
        return lineWidth(width).lineColor(color);
    }

   
    public ShapeBuilder lineWidth(int lineWidth) {
        this.lineWidth = DeviceInfo.convertDpToPx(lineWidth);
        return this;
    }

    public ShapeBuilder lineColor(int lineColor) {
        this.lineColor = lineColor;
        return this;
    }
    
    public ShapeBuilder corner(float cornerRadius) {
        this.cornerRadius = DeviceInfo.convertDpToPx(cornerRadius);
        return this;
    }

   
    public ShapeBuilder corner() {
        return corner(defaultCornerRadius);
    }
    
    public ShapeBuilder dash() {
        return dashWidth(defaultDashWidth).dashGap(defaultDashGap);
    }
}

通过链式点的方式对其进行初始化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值