当前位置: 首页 > news >正文

Android 自定义进度条:实现渐变色和圆角效果

CustomProgressBar 自定义控件,用于展示数据进度条。支持渐变颜色、圆角效果,适用于需要直观展示任务完成度或进度的场景,且可以使用DataBinding进行实时更新。

一、主要功能:

  1. 进度展示:支持动态设置进度值,范围为 0~100

  2. 渐变颜色:支持线性渐变,自定义渐变起始色与结束色

  3. 圆角设计:提供圆角进度条效果,圆角半径可自定义

  4. 背景色可定制:支持动态设置背景颜色

  5. 自定义属性支持:提供多种 XML 属性配置,可直接在布局文件中设置默认值:

    1. progress:初始进度值。

    2. progressColorStart:渐变起始颜色。

    3. progressColorEnd:渐变结束颜色。

    4. backgroundColor:背景颜色。

    5. cornerRadius:圆角半径。


二、适用场景:

  1. 加载进度显示(如文件下载进度)

  2. 任务完成度展示(如每日目标完成情况)

  3. 数据比例可视化(如投票结果、性能占比)

三、效果图

四、自定义组件代码及配置

  1. 组件代码
    /**
     * @Description: 自定义数据进度条
     * @Author: 会叫的青蛙
     * @Date: 2025/1/14 11:42
     */
    class CustomProgressBar @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
    ) : View(context, attrs, defStyleAttr) {
    
        private var progress = 0f // 当前进度 (0~100)
        private var progressColorStart = Color.BLUE // 渐变开始色
        private var progressColorEnd = Color.CYAN // 渐变结束色
        private var backgroundColor = Color.LTGRAY // 背景色
        private var cornerRadius = 20f // 圆角半径,默认20dp
    
        private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    
        init {
            //自定义属性
            context.theme.obtainStyledAttributes(attrs, R.styleable.CustomProgressBar, 0, 0).apply {
                try {
                    progress = getFloat(R.styleable.CustomProgressBar_progress, 0f)
                    progressColorStart = getColor(R.styleable.CustomProgressBar_progressColorStart, Color.BLUE)
                    progressColorEnd = getColor(R.styleable.CustomProgressBar_progressColorEnd, Color.CYAN)
                    backgroundColor = getColor(R.styleable.CustomProgressBar_backgroundColor, Color.LTGRAY)
                    cornerRadius = getDimension(R.styleable.CustomProgressBar_cornerRadius, 20f)
                } finally {
                    recycle()
                }
            }
        }
    
        @SuppressLint("DrawAllocation")
        override fun onDraw(canvas: Canvas) {
            super.onDraw(canvas)
    
            val width = width.toFloat()
            val height = height.toFloat()
    
            // 绘制背景 (带圆角)
            backgroundPaint.color = backgroundColor
            canvas.drawRoundRect(0f, 0f, width, height, cornerRadius, cornerRadius, backgroundPaint)
    
            // 绘制渐变进度 (带圆角)
            val progressWidth = width * (progress / 100)
            val gradient = LinearGradient(
                0f, 0f, progressWidth, 0f,
                progressColorStart, progressColorEnd,
                Shader.TileMode.CLAMP
            )
            progressPaint.shader = gradient
            canvas.drawRoundRect(0f, 0f, progressWidth, height, cornerRadius, cornerRadius, progressPaint)
        }
    
        /**
         * 设置进度
         */
        fun setProgress(value: Float) {
            progress = value.coerceIn(0f, 100f)
            invalidate() // 重绘视图
        }
    
        /**
         * 设置背景颜色
         */
        override fun setBackgroundColor(color: Int) {
            backgroundColor = color
            invalidate()
        }
    
        /**
         * 设置渐变颜色
         */
        fun setGradientColors(startColor: Int, endColor: Int) {
            progressColorStart = startColor
            progressColorEnd = endColor
            invalidate()
        }
    
        /**
         * 设置圆角半径
         */
        fun setCornerRadius(radius: Float) {
            cornerRadius = radius
            invalidate()
        }
    
    }

2.自定义属性

<!--自定义数据进度条属性-->
<declare-styleable name="CustomProgressBar">
    <attr name="progress" format="float" />
    <attr name="progressColorStart" format="color" />
    <attr name="progressColorEnd" format="color" />
    <attr name="backgroundColor" format="color" />
    <attr name="cornerRadius" format="dimension" />
</declare-styleable>

五、使用方法:

  1. 在布局中引用:
    <com.view.CustomProgressBar
        android:id="@+id/customProgressBar"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        app:progress="50"
        app:progressColorStart="@color/blue"
        app:progressColorEnd="@color/cyan"
        app:backgroundColor="@color/gray"
        app:cornerRadius="10dp" />
  2. 在代码中动态设置:
    customProgressBar.setProgress(75f) // 设置进度
    customProgressBar.setBackgroundColor(Color.LTGRAY) // 设置背景色
    customProgressBar.setGradientColors(Color.RED, Color.YELLOW) // 设置渐变色
    customProgressBar.setCornerRadius(15f) // 设置圆角半径
  3. 使用viewModel进行数据双向绑定
    <com.view.CustomProgressBar
        android:layout_width="match_parent"
        android:layout_height="8dp"
        android:layout_marginTop="14dp"
        android:layout_marginBottom="8dp"
        app:backgroundColor="@{viewModel.cpuState == true ? @color/progress_bg_color_red : @color/progress_bg_color_blue}"
        app:progress="@{viewModel.cpuUsageRateData}"
        app:progressColorEnd="@{viewModel.cpuState == true ? @color/progress_end_color_red : @color/progress_end_color_blue}"
        app:progressColorStart="@{viewModel.cpuState == true ? @color/progress_start_color_red : @color/progress_start_color_blue}" />

    注意事项:默认情况下,数据绑定框架只能识别 Android 系统提供的标准属性(如 android:textandroid:visibility 等)。对于自定义的属性(如 progressColorStartprogress),框架本身无法直接解析和绑定。

    通过 @BindingAdapter,可以定义自定义属性与组件方法之间的绑定规则,使得数据绑定框架能够正确识别这些属性。

    /**
     * @Description: 自定义数据进度条DataBinding适配器
     * @Author: 会叫的青蛙
     * @Date: 2025/1/14 15:42
     */
    object BindingAdapters {
    
        // 绑定进度条颜色
        @BindingAdapter("progressColorStart", "progressColorEnd")
        @JvmStatic
        fun setProgressColor(view: CustomProgressBar, startColor: Int, endColor: Int) {
            view.setGradientColors(startColor, endColor)
        }
    
        // 绑定进度
        @BindingAdapter("progress")
        @JvmStatic
        fun setProgress(view: CustomProgressBar, progress: Float) {
            view.setProgress(progress)
        }
    
        // 绑定背景色
        @BindingAdapter("backgroundColor")
        @JvmStatic
        fun setBackgroundColor(view: CustomProgressBar, color: Int) {
            view.setBackgroundColor(color)
        }
    
    }

相关文章:

  • 基于大语言模型的推荐系统(2)
  • Pytest自定义测试用例执行顺序
  • docker本地镜像源搭建
  • 基于定制开发开源AI大模型S2B2C商城小程序的商品选品策略研究
  • Spring Boot集成Jetty、Tomcat或Undertow及支持HTTP/2协议
  • 基于PyTorch实现的自适应注意力卷积网络(AACN)详解
  • 【C++】C/C++中的类型转换
  • SpringBoot 使用 spring.profiles.active 来区分不同环境配置
  • 【AIGC系列】3:Stable Diffusion模型原理介绍
  • WiseFlow本地搭建实录---保姆教程
  • AWS跨账号服务全解析:安全共享资源的最佳实践
  • 3.【基于深度学习YOLOV11的车辆类型检测系统】
  • Go在1.22版本修复for循环陷阱
  • Kylin麒麟操作系统 | 系统监控
  • Element-Plus,使用 El-form中 的 scroll-to-error 没有效果问题记录
  • openlayers结合turf geojson面获取面积和中心点
  • redis存取list集合
  • 腿足机器人之十三-强化学习PPO算法
  • 【AI+智造】用DeepSeek分析设备温度、振动、速度、加速度量化数据:南通制造业数字化转型的“智能引擎” ——基于设备全生命周期管理的开源技术方案
  • 光谱相机的市场发展趋势
  • 批发网站大全最便宜卖1688/高明搜索seo
  • 如何设计网站的首页/长沙靠谱seo优化
  • 网站建设与运营市场开发方案/关键词收录
  • 网站建设公司如何推广/常德政府网站
  • 广州购物商城网站开发/佛山百度seo点击软件
  • 顺义做网站公司/最新热搜榜