Android自定义旋转进度条

一、前言

在实际开发中,当数据加载时候我们要显示一个圆形旋转当进度条。这个系统提供当有,但是UI给的往往会有些变动,例如如下效果
在这里插入图片描述

这时候该怎么做呢?通常网上的做法是继承View进行自己绘制。但是为什么不能继承现有的进度条进行绘制呢?

二、编码

1、拓展带文字的进度条

首先我们选择新版的ContentLoadingProgressBar来进行继承拓展(因为这个相对于ProgressBar来说用户体验上会有一点优化)。然后在继承的控件里面绘制文字,然后选择设置进度条的背景色。代码如下:

class CustomProgress: ContentLoadingProgressBar {

    //中心显示的文字
    private var centerText = "Scanning..."
    private var textColor = Color.parseColor("#5ED9ED")
    set(value) {
        field = value
        postInvalidate()
    }

    //绘制的画笔
    private val textPaint = Paint()

    constructor(context: Context) : super(context){
        initPaint()
    }
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs){
        initPaint()
    }

    private fun initPaint(){
        textPaint.color = textColor
        textPaint.textSize = PxUtils.spToPx(12,context).toFloat()
        textPaint.style = Paint.Style.FILL
        textPaint.isAntiAlias = true
        textPaint.textAlign = Paint.Align.CENTER
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvasCenterText(canvas)
    }

    /**
     * 绘制中心的文字
     */
    private fun canvasCenterText(canvas: Canvas?){
        canvas?.drawText(centerText, (width / 2).toFloat(), (width / 2).toFloat(), textPaint)
    }

}

2、创建动画背景

../app/res/文件夹下面创建anim文件夹。创建anim_progress.xml文件。内容如下:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="50"
    android:drawable="@mipmap/img_processing_ring"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="1080"/><!-- 值越大速度越快 -->

其中动画文件里面的drawable引用的是一个旋转的图片,也可以自定义。

使用如下:

<com.custom.view.CustomProgress
        android:id="@+id/media_progressbar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:indeterminateDrawable="@anim/anim_progress"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:visibility="visible"/>

三、参考链接

  1. Android 项目中 Loading 对话框的优化_weixin_38754349的博客-CSDN博客
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值