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

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

34资源网2022-06-27446

前言

效果图

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

圆圈和文字状态

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

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

文字居中

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

分享给朋友:

相关文章

用侠肝义胆造句30句

用侠肝义胆造句30句

1、李大哥侠肝义胆,受到四邻的交口称赞。…

适合普通人做的小本创业点子

适合普通人做的小本创业点子

适合普通人做的小本创业生意有什么??随着零售行业的兴起,小型超市便利店生意成为创业者首选的项目之一,主要原因在于:投入资金小、回笼快,不需要太大的现金流来支撑、一年半左右就能回本。这对于拥有一部分闲置资金,想创业的投资者来说简直是很好的创业…

调整心态温暖哲理经典语录,看这些语录能够调整心态

调整心态温暖哲理经典语录,看这些语录能够调整心态

取得成功是他人不成功时仍在坚持不懈。若自身不作出一点外貌,别人想拉你一把都不知道你的手在哪儿。直至你不会再找我聊,直至你找不着我,直至最终,你一直在某一瞬间猛地想起我。但是,那个时候,被你弄丢的我就确实早已没有了,也再不想要你再找回家了。理…

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

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

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

视频号怎么开通微信小商店技巧流程方法分享

视频号怎么开通微信小商店技巧流程方法分享

这两年直播的风口一直高居不下,微信终于也跟上了直播热潮,视频号直播新增购物车功能,已经开通了小商店的视频号,可以在直播中上架小商店商品,直播过程可以展示并售卖商品。视频号直播带货无疑让更多创作者加入其中,同时也意味着视频号功能的进一步完善,…