当前位置:首页 > 谈天说地

Android新建水平节点进度条示例

34资源网2022-06-27312

前言

效果图

前几天在网上没有找到合适的横向节点进度条,自己动手写了一个,先来看看效果图

圆圈和文字状态

我们看到小圆圈和文字有几种状态呢?

  • 第一个空心的小圆圈是处理完成的状态
  • 第二个实心的小圆圈是处理中的状态
  • 第三个实心的小圆圈是待处理的状态
    没错,我们看到了小圆圈和文字有三种处理状态

文字居中

我们写一个类继承自appcompattextview,通过onmeasure方法得到控件的宽高,通过paint的gettextbounds()也可以知道文字的宽高,我们看到有5个节点需要处理,我们把屏幕划分成5个等份,每个等份都相等,这里用itemwidth 表示每个相同的等份。文字居中的写法很简单,

itemwidth / 2 - textwidth / 2

代码

package cn.wwj.customview.widget
import android.content.context
import android.graphics.canvas
import android.graphics.color
import android.graphics.paint
import android.graphics.rect
import android.text.textpaint
import android.util.attributeset
import android.util.log
import androidx.annotation.nullable
import androidx.appcompat.widget.appcompattextview
import androidx.core.content.contextcompat
import androidx.core.view.margintop
import cn.wwj.customview.r
import cn.wwj.customview.dp2px
import cn.wwj.customview.sp2px
/**
 * 节点进度条
 */
class nodepointprocessbar : appcompattextview {
    /**
     * 文字画笔
     */
    private lateinit var mtextpaint: textpaint
    /**
     * 圆画笔
     */
    private lateinit var mcirclepaint: paint
    private var isdebug = false
    /**
     * 已完成文字颜色
     */
    private var mcompletetextcolor: int = contextcompat.getcolor(context, android.r.color.black)
    /**
     * 处理中文字颜色
     */
    private var mprocesstextcolor: int = contextcompat.getcolor(context, r.color.purple)
    /**
     * 待处理的文字颜色
     */
    private var mwaitprocesstextcolor: int = contextcompat.getcolor(context, r.color.gray_text)
    /**
     * 绘制的节点个数,由底部节点标题数量控制
     */
    private var mcirclecount = 0
    private var tag = "nodepointprocessbar"
    /**
     * 圆的半径
     */
    private var mcircleradius = 5f.dp2px()
    /**
     * 圆圈的边框线
     */
    private var mcircleborder = 1f.dp2px()
    /**
     * 线的宽度
     */
    private var mlinewidth = 1f.dp2px()
    /**
     * 线之间的左右边距
     */
    private var mlinemargin = 4f.dp2px()
    /**
     * 文字和圆圈之间的距离
     */
    var mtextcirclemargin = 7f.dp2px()
    /**
     * 文字的水平边距
     */
    private var mtextleftrightmargin = 8f.dp2px()
    /**
     * 计算内容的高度 和 宽度
     */
    private var mcontentheight = 0f
    private var mcontentwidth = 0f
    /**
     * 节点底部的文字列表
     */
    private var mtextlist: list<string> = mutablelistof()
    /**
     * 选中项集合
     */
    private var mprocessindexset: set<int> = mutablesetof()
    /**
     * 文字同宽高的矩形,用来测量文字
     */
    private var mtextboundlist: mutablelist<rect> = mutablelistof()
    /**
     * 计算文字宽高的矩形
     */
    private val mrect = rect()
    constructor(context: context) : this(context, null)
    constructor(context: context, @nullable attrs: attributeset?) : this(context, attrs, 0)
    constructor(
        context: context,
        @nullable attrs: attributeset?,
        defstyleattr: int
    ) : super(context, attrs, defstyleattr) {
        val appearance = context.obtainstyledattributes(attrs, r.styleable.nodepointprocessbar)
        mcompletetextcolor = appearance.getcolor(
            r.styleable.nodepointprocessbar_completedtextcolor, mcompletetextcolor
        )
        mwaitprocesstextcolor = appearance.getcolor(
            r.styleable.nodepointprocessbar_processtextcolor, mwaitprocesstextcolor
        )
        mprocesstextcolor =
            appearance.getcolor(
                r.styleable.nodepointprocessbar_waitprocesstextcolor,
                mprocesstextcolor
            )
        isdebug = appearance.getboolean(
            r.styleable.nodepointprocessbar_isdebug, isdebug
        )
        mtextcirclemargin = appearance.getdimension(
            r.styleable.nodepointprocessbar_textcirclemargin, mtextcirclemargin
        )
        mtextleftrightmargin = appearance.getdimension(
            r.styleable.nodepointprocessbar_textleftrightmargin, mtextleftrightmargin
        )
        mcircleradius = appearance.getdimension(
            r.styleable.nodepointprocessbar_npbcircleradius, mcircleradius
        )
        mcircleborder = appearance.getdimension(
            r.styleable.nodepointprocessbar_circleborder, mcircleborder
        )
        mlinewidth = appearance.getdimension(
            r.styleable.nodepointprocessbar_linewidth, mlinewidth
        )
        mlinemargin = appearance.getdimension(
            r.styleable.nodepointprocessbar_linemargin, mlinemargin
        )
        initpaint()
        show(mtextlist, mprocessindexset)
    }
    /**
     * 初始化画笔属性
     */
    private fun initpaint() {
        // 设置文字画笔
        mtextpaint = textpaint()
        mtextpaint.isantialias = true
        mtextpaint.textsize = textsize
        mtextpaint.color = mwaitprocesstextcolor
        // 设置圆圈画笔
        mcirclepaint = paint()
        mcirclepaint.isantialias = true
        mcirclepaint.color = mprocesstextcolor
        mcirclepaint.style = paint.style.stroke
        mcirclepaint.strokewidth = mcircleborder
    }
    override fun onmeasure(widthmeasurespec: int, heightmeasurespec: int) {
        super.onmeasure(widthmeasurespec, heightmeasurespec)
        val widthmode = measurespec.getmode(widthmeasurespec)
        val heightmode = measurespec.getmode(heightmeasurespec)
        log.d(tag, "---------------onmeasure()")
        measuretext()
        val widthsize = if (measurespec.exactly == widthmode) {
            measurespec.getsize(widthmeasurespec)
        } else {
            mcontentwidth.toint()
        }
        val heightsize = if (measurespec.exactly == heightmode) {
            measurespec.getsize(heightmeasurespec)
        } else {
            mcontentheight.toint()
        }
        /**
         * 设置控件的宽高
         */
        setmeasureddimension(widthsize, heightsize)
        calccontentwidthheight()
    }
    /**
     * 测量文字的长宽,将文字视为rect矩形
     */
    private fun measuretext() {
        log.d(tag, "---------------measuretext()")
        mtextboundlist.clear()
        for (name in mtextlist) {
            mrect.setempty()
            mtextpaint.gettextbounds(name, 0, name.length, mrect)
            mtextboundlist.add(mrect)
        }
    }
    /**
     * 获取内容的高度,如果控件的宽度小于内容的宽度,意味着一行放不下了,文字的大小减小1sp,重新测量文字的宽高,重新
     */
    private fun calccontentwidthheight() {
        // 一开始没有传递文字的
        mcontentheight = if (mtextboundlist.isnotempty()) {
            mcircleradius * 2 + mtextcirclemargin + mrect.height() + getbaseline(mtextpaint)
        } else {
            mtextpaint.gettextbounds("中", 0, 1, mrect)
            mcircleradius * 2 + mtextcirclemargin + mrect.height() + getbaseline(mtextpaint)
        }
        if (measuredwidth == 0 || mtextboundlist.isempty()) {
            return
        }
        mcontentwidth = 0f
        for (rect in mtextboundlist) {
            mcontentwidth += rect.width()
        }
        log.d(tag, "---------------measuredwidth=$measuredwidth,mcontentwidth=$mcontentwidth")
        // 如果控件的宽度小于内容的宽度加文本的边距,意味着一行放不下了,文字的大小减小1sp,重新测量文字的宽高后,设置控件得高度
        // 如果控件的宽度大于内容的宽度加文本的边距,意味着一行放得下,设置控件得高度
        if (measuredwidth - mcontentwidth < (mtextleftrightmargin * (mtextlist.size - 1))) {
            mtextpaint.textsize = mtextpaint.textsize - 1f.sp2px()
            measuretext()
            calccontentwidthheight()
            return
        }
        setmeasureddimension(measuredwidth, mcontentheight.toint())
    }
    override fun ondraw(canvas: canvas) {
        //若未设置节点标题或者选中项的列表,则取消绘制
        if (mtextlist.isempty() || mtextboundlist.isempty()) {
            return
        }
        //画灰色圆圈的个数
        mcirclecount = mtextlist.size
        // 每一段文字的y坐标
        val texty = getbaseline(mtextpaint) + height / 2 + margintop / 2
        mcirclepaint.strokewidth = mcircleborder
        //绘制文字和圆形
        for (i in 0 until mcirclecount) {
            if (mprocessindexset.contains(i)) {
                // 正在处理中
                if (mprocessindexset.size == i + 1) {
                    mcirclepaint.style = paint.style.fill
                    // 正在处理中的文字颜色
                    mtextpaint.color = mprocesstextcolor
                    mcirclepaint.color = mprocesstextcolor
                } else {
                    //处理完成圆圈空心
                    mcirclepaint.style = paint.style.stroke
                    //处理完成文字颜色
                    mtextpaint.color = mcompletetextcolor
                    mcirclepaint.color = mprocesstextcolor
                }
            } else {
                //待处理
                mcirclepaint.color = mwaitprocesstextcolor
                mcirclepaint.style = paint.style.fill
                mtextpaint.color = mwaitprocesstextcolor
            }
            //每一段文字宽度
            val textwidth = mtextboundlist[i].width()
            // 每一段宽度
            val itemwidth = width * 1f / mcirclecount
            // 每一段文字居中
            // |----text----|----text----|
            //    一段文字       一段文字
            //每一段文字起始的x坐标
            val textx = itemwidth / 2f - textwidth / 2f + i * itemwidth
            canvas.drawtext(mtextlist[i], textx, texty, mtextpaint)
            //每一个圆圈的y坐标
            val circley = height / 2f - mcircleradius - mtextcirclemargin / 2
            //每一个圆圈的x坐标
            val circlex = itemwidth / 2 + i * itemwidth
            canvas.drawcircle(
                circlex,
                circley,
                mcircleradius,
                mcirclepaint
            )
            // 画线,两个圆圈之间一条线段
            mcirclepaint.strokewidth = mlinewidth
            if (i < mcirclecount - 1) {
                //已经处理过的线颜色
                if (mprocessindexset.contains(i + 1)) {
                    mcirclepaint.color = mprocesstextcolor
                } else {
                    // 待处理的线段颜色
                    mcirclepaint.color = mwaitprocesstextcolor
                }
                // 线段起始 x 坐标
                val linestartx = itemwidth * i + itemwidth / 2f + mcircleradius + mlinemargin
                // 线段结束 x 坐标
                val lineendx =
                    itemwidth * i + itemwidth + itemwidth / 2f - mcircleradius - mlinemargin
                canvas.drawline(
                    linestartx,
                    circley,
                    lineendx,
                    circley,
                    mcirclepaint
                )
            }
            log.d("tag", "--------itemwidth=$itemwidth")
        }
        if (isdebug) {
            mcirclepaint.color = color.red
            canvas.drawline(
                0f,
                height / 2f - 1f.dp2px() / 2,
                width * 1f,
                height / 2f + 1f.dp2px() / 2,
                mcirclepaint
            )
        }
    }
    /**
     * 供外部调用,展示内容
     * @param titles 要展示的内容列表
     * @param progressindexset 节点选中项集合
     */
    fun setnodedata(titles: list<string>, progressindexset: set<int>) {
        mtextlist = titles
        mprocessindexset = progressindexset
        measuretext()
        calccontentwidthheight()
        invalidate()
    }
    /**
     * 获取文字的基线
     */
    private fun getbaseline(p: paint): float {
        val fontmetrics: paint.fontmetrics = p.fontmetrics
        return (fontmetrics.bottom - fontmetrics.top) - fontmetrics.descent
    }
}

这里的show()方法用于展示内容,第一个参数要展示的内容列表,第二个参数代表节点选中项集合,紧接着测量文字的宽高,调用这个方法calccontentwidthheight()获取文字的高度,然后设置文字的宽高,代码中的注释写的很详细,我们就不再细说了

声明下style

attrs.xml

 <declare-styleable name="nodepointprocessbar">
        <attr name="completedtextcolor" format="color" />
        <attr name="processtextcolor" format="color" />
        <attr name="waitprocesstextcolor" format="color" />
        <attr name="textcirclemargin" format="dimension" />
        <attr name="textleftrightmargin" format="dimension" />
        <attr name="npbcircleradius" format="dimension" />
        <attr name="circleborder" format="dimension" />
        <attr name="linewidth" format="dimension" />
        <attr name="linemargin" format="dimension" />
        <attr name="isdebug" format="boolean" />
    </declare-styleable>

新建一个extendutil.kt文件

fun int.sp2px(): int {
    val displaymetrics = resources.getsystem().displaymetrics
    return typedvalue.applydimension(typedvalue.complex_unit_sp, this.tofloat(), displaymetrics)
        .toint()
}
fun float.sp2px(): float {
    val displaymetrics = resources.getsystem().displaymetrics
    return typedvalue.applydimension(typedvalue.complex_unit_sp, this, displaymetrics)
}
fun int.dp2px(): int {
    val displaymetrics = resources.getsystem().displaymetrics
    return typedvalue.applydimension(typedvalue.complex_unit_dip, this.tofloat(), displaymetrics)
        .toint()
}
fun float.dp2px(): float {
    val displaymetrics = resources.getsystem().displaymetrics
    return typedvalue.applydimension(typedvalue.complex_unit_dip, this, displaymetrics)
}

接着创建布局文件

activity_node_progress_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.constraintlayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <cn.wwj.customview.widget.nodepointprocessbar
        android:id="@+id/nodepointpb"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textsize="18sp"
        android:layout_marginhorizontal="10dp"
        app:layout_constraintbottom_tobottomof="parent"
        app:layout_constraintleft_toleftof="parent"
        app:isdebug="false"
        app:linewidth="1dp"
        app:linemargin="5dp"
        app:layout_constraintright_torightof="parent"
        app:layout_constrainttop_totopof="parent" />
</androidx.constraintlayout.widget.constraintlayout>

再activity中使用它

package cn.wwj.customview
import android.os.bundle
import android.os.handler
import android.os.looper
import androidx.appcompat.app.appcompatactivity
import cn.wwj.customview.widget.nodepointprocessbar
/**
 * 节点进度activity
 */
class nodeprogressbaractivity : appcompatactivity() {
    /**
     * 数据结合
     */
    private val mtextlist: list<string> = mutablelistof("提交申请", "商家处理", "寄回商品", "商家退款", "退款成功")
    /**
     * 正在处理的节点索引结合
     */
    private var mprogressindexset: set<int> = mutablesetof(0, 1,2,3,4,6)
    override fun oncreate(savedinstancestate: bundle?) {
        super.oncreate(savedinstancestate)
        setcontentview(r.layout.activity_node_progress_bar)
        val nodepointpb: nodepointprocessbar = findviewbyid(r.id.nodepointpb)
        handler(looper.getmainlooper()).postdelayed({
            nodepointpb.setnodedata(mtextlist, mprogressindexset)
        }, 1000)
    }
}

mtextlist数据集合

mprogressindexset正在处理的节点索引结合,创建handler对象模拟调用网络接口,1秒后返回数据

节点全部处理完成.png

项目地址,在customview这模块下

https://github.com/githubwwj/myandroid

以上就是android新建水平节点进度条示例的详细内容,更多关于android水平节点进度条的资料请关注萬仟网其它相关文章!

看完文章,还可以扫描下面的二维码下载快手极速版领4元红包

快手极速版二维码

快手极速版新人见面礼

除了扫码领红包之外,大家还可以在快手极速版做签到,看视频,做任务,参与抽奖,邀请好友赚钱)。

邀请两个好友奖最高196元,如下图所示:

快手极速版邀请好友奖励

扫描二维码推送至手机访问。

版权声明:本文由34楼发布,如需转载请注明出处。

本文链接:https://www.34l.com/post/18117.html

分享给朋友:

相关文章

李开复经典语录大全

李开复经典语录大全

开复,你是想一辈子写一堆像废纸一样的学术论文呢?还是想用产品改变世界?”这是当时苹果公司的副总裁戴夫?耐格尔举着一杯透亮的自酿葡萄酒向他发出加入邀请。正是这句话点燃了李开复心中多年“世界因你不同”的梦想。他放弃了对终身教授职位的追求,做出了…

coco奶茶店加盟费大概多少钱?有哪些优势?

coco奶茶店加盟费大概多少钱?有哪些优势?

CoCo奶茶来自宝岛台湾的奶茶加盟连锁品牌,以绿色健康休闲奶茶饮品为主打的连锁机构,在中国及东南亚地区拥有众多加盟连锁店。相信很多人都想加盟这个奶茶店吧?那么,coco奶茶店加盟费大概多少钱?加盟有哪些优势呢?下面小编就详细和大家介绍下吧。…

年轻人不讲武德和耗子尾汁什么意思?什么梗?

年轻人不讲武德和耗子尾汁什么意思?什么梗?

最近经常在朋友圈,抖音上面刷到一些视频评论说年轻人不讲5的和耗子尾汁,小编看着感觉好奇怪,刚开始有点懵逼,结果去网上查了一下才知道,这是太极大师马保国老师讲的。究竟这个梗是怎么来的呢?其实,刚开始人家只是取笑这个马保国大师的梗,后面没有想到…

分享30句用被刺造句的句子

分享30句用被刺造句的句子

1、黄昏已经谢去,夜幕早已铺开。高高的法国梧桐,被刺眼的白色路灯照亮。在黑色的夜空里镶了一圈又一圈攫绿,有时被拂过的夜风飘动,发出轻轻的沙沙声,只那么一阵,就消失在无限的宁静之中。…

抖音传话筒项目(傻瓜式复制粘贴轻松月入3000+)

抖音传话筒项目(傻瓜式复制粘贴轻松月入3000+)

可能你觉得你写不出优秀的文案,可能你觉得你没办法配音,可能你觉得不好意思露脸,但又想通过抖音来赚钱,那么今天给大家来说说这个抖音传话筒项目,只需要复制粘贴,一个月轻松赚到3000+,无需露脸配音,更加不需要写文案。…

华为、苹果,为何“盯”上二手机?

华为、苹果,为何“盯”上二手机?

图源:摄图网 编者按:本文来自微信公众号松果财经(ID:songguocaijing1),创业邦经授权转载 继苹果后,华为近日也正式官宣开启二手手机业务,并表示此举是为了提升电子产品的循环再利用。华为官方承诺所售二手手机均为正品且经过严格把…