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

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

34资源网2022-06-27327

前言

效果图

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

圆圈和文字状态

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

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

文字居中

我们写一个类继承自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

分享给朋友:

相关文章

女装加盟哪个品牌可靠?艾丽哲这个牌子不错哦

女装加盟哪个品牌可靠?艾丽哲这个牌子不错哦

女装行业一直发展都不错,女装加盟哪个品牌可靠?在众多的女装品牌当中,艾丽哲女装凭借优良的口碑和超高的人气,在行业当中占有一定的优势,是好的,当中非常可靠的品牌,在激烈的市场当中,凭借超高的实力,得到了无数加盟商的认可,赚钱轻松,发展潜力大,…

名人名言大全,分享100句

名人名言大全,分享100句

名人名言100句:…

华盛顿:自己不能胜任的事情,切莫轻易答应别人

华盛顿:自己不能胜任的事情,切莫轻易答应别人

自己不能胜任的事情,切莫轻易答应别人,一旦答应了别人,就必须实践自己的诺言。——华盛顿 这则名言告诉我们什么道理?我们应该怎么做?…

现在开一家vr游戏体验馆投资创业要多少钱?

现在开一家vr游戏体验馆投资创业要多少钱?

现在开一家vr游戏体验馆投资创业要多少钱?这个涉及到的东西很多,比如你的店铺开在市区还是乡下,是开在热闹地方还是比较冷清的地方,另外还要看你的店面有多大,设备有多少台,以及其他的零零碎碎加起来,就能知道开一家vr游戏体验馆需要多少钱了。…

直播间里“拆盲盒”,二手电商平台「Whatnot」拆出15亿美元丨快鲤鱼海外

直播间里“拆盲盒”,二手电商平台「Whatnot」拆出15亿美元丨快鲤鱼海外

靠着直播带货和“拆盲盒”,二手潮品电商平台 Whatnot 在今年已经完成了3轮融资,公司估值达到 15 亿美元,成立2年便跻身独角兽之列。 通过商品认证转卖、直播拍卖、直播间开“盲盒”等看似有点“中国味”的玩儿法,Whatnot一改美国二…

没想到,理想汽车成了“蔚小理”中最有钱的公司

没想到,理想汽车成了“蔚小理”中最有钱的公司

图源:摄图网 编者按:本文来自微信公众号连线出行(ID:lianxianchuxing),作者:周雄飞,创业邦经授权转载 曾几何时,理想汽车还是“蔚小理”三兄弟之中最落魄的一家。 理想汽车于2015年7月由李想创立,虽然与蔚来、小鹏相比起步…