熊熊出没 发表于 2025-3-8 10:50:00

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

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

一、重要功能:


[*] 进度展示:支持动态设置进度值,范围为 0~100
[*] 渐变颜色:支持线性渐变,自定义渐变起始色与结束色
[*] 圆角计划:提供圆角进度条效果,圆角半径可自定义
[*] 配景色可定制:支持动态设置配景颜色
[*] 自定义属性支持:提供多种 XML 属性配置,可直接在布局文件中设置默认值:

[*] progress:初始进度值。
[*] progressColorStart:渐变起始颜色。
[*] progressColorEnd:渐变结束颜色。
[*] backgroundColor:配景颜色。
[*] cornerRadius:圆角半径。

二、适用场景:


[*] 加载进度显示(如文件下载进度)
[*] 任务完成度展示(如逐日目标完成环境)
[*] 数据比例可视化(如投票结果、性能占比)
三、效果图:

https://i-blog.csdnimg.cn/direct/a7e5199d71084176900cbd7f9249e8a3.png
四、自定义组件代码及配置


[*] 组件代码

/**
* @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>
五、使用方法:


[*] 在布局中引用:

<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" />
[*] 在代码中动态设置:

customProgressBar.setProgress(75f) // 设置进度
customProgressBar.setBackgroundColor(Color.LTGRAY) // 设置背景色
customProgressBar.setGradientColors(Color.RED, Color.YELLOW) // 设置渐变色
customProgressBar.setCornerRadius(15f) // 设置圆角半径
[*] 使用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:text、android:visibility 等)。对于自定义的属性(如 progressColorStart、progress),框架本身无法直接解析和绑定。
通过 @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)
    }

}

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Android 自定义进度条:实现渐变色和圆角效果