Android自定义View之审核进度条

概述:
在做商城类的App时,都会有售后的需求,而售后流程通常会因为不同的业务,而分为不确定的几个步骤,如下图所示:
image.png
那么问题就来了,像这样的效果如何实现呢?让我们先放下这个问题,先看看UI模仿的京东原图是怎样的:

动图:
image.gif

从上面的效果图中我们可以观察到,当步骤少的话,等分居中显示,当步骤多的话,可以横向拖动显示。

一 分析

1 需要实现的效果:相信不要多言,上面已经完全展示。
2 需要注意的点:步骤不固定,文字和图片居中对齐,文字可能多行,多行的文字也是对称的。

二 思路

相同的效果,会有不同的实现思路。这里提供两个方法实现:
1 将一个步骤单独作为自定义view实现。
2 将所有步骤做为自定义view实现。
本文将才用第一种实现方式,实现我们的效果。将一个步骤作为自定义view时,我们还可以再分成三个部分: 左边线,中间图片,右边线。

三 实现

1 自定义属性(在values目录下新建attrs.xml):
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 申请进度的自定义view-->
    <declare-styleable name="AuditProgressView">
        <!--当前步骤是否完成 -->
        <attr name="apv_isCurrentComplete" format="boolean" />
        <!--下一个步骤是否完成 -->
        <attr name="apv_isNextComplete" format="boolean" />
        <!--是不是第一个步骤 -->
        <attr name="apv_isFirstStep" format="boolean" />
        <!--是不是最后一个步骤 -->
        <attr name="apv_isLastStep" format="boolean" />
        <!--共有几个步骤 -->
        <attr name="apv_stepCount" format="integer" />
        <!--步骤提示 -->
        <attr name="apv_text" format="string|reference" />
    </declare-styleable>

</resources>

上面的属性是必须定义的属性。对于其他例如文字颜色 线条颜色 文字大小之类的属性都没有定义,有需要的可以自己复制源码进行修改。

布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center"
    android:orientation="vertical">


    <!--动态设置数据-->
    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="none">
        <LinearLayout
            android:id="@+id/ll_audit_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal" />
    </HorizontalScrollView>
    
    <!--分割线-->
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_margin="3dp"
        android:background="@android:color/darker_gray" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="12dp"
        android:gravity="center_horizontal"
        android:text="上面代码动态设置 下面xml布局设置"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_margin="3dp"
        android:background="@android:color/darker_gray" />


    <!--XML静态设置数据-->
    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:scrollbars="none">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <com.p.h.view.AuditProgressView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:apv_isCurrentComplete="true"
                app:apv_isFirstStep="true"
                app:apv_isLastStep="false"
                app:apv_isNextComplete="true"
                app:apv_stepCount="4"
                app:apv_text="提交行程" />
            <com.p.h.view.AuditProgressView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:apv_isCurrentComplete="true"
                app:apv_isFirstStep="false"
                app:apv_isLastStep="false"
                app:apv_isNextComplete="true"
                app:apv_stepCount="4"
                app:apv_text="支付费用" />
            <com.p.h.view.AuditProgressView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:apv_isCurrentComplete="false"
                app:apv_isFirstStep="false"
                app:apv_isLastStep="false"
                app:apv_isNextComplete="false"
                app:apv_stepCount="4"
                app:apv_text="乘车出行" />
            <com.p.h.view.AuditProgressView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:apv_isCurrentComplete="false"
                app:apv_isFirstStep="false"
                app:apv_isLastStep="true"
                app:apv_isNextComplete="false"
                app:apv_stepCount="4"
                app:apv_text="支付尾款" />
        </LinearLayout>
    </HorizontalScrollView>

</LinearLayout>

自定义View的整体代码:

package com.p.h.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import androidx.annotation.Nullable;
import com.p.h.R;

/**
 * describe: 自定义支付进度条 PanHui
 */
public class AuditProgressView extends View {
    // 标记该步骤是否完成
    private boolean mIsCurrentComplete;
    // 标记下一个步骤是否完成
    private boolean mIsNextComplete;
    // 根据是否完成的标记 确定绘制的图片
    private Bitmap audit_drawBitmap;
    // 绘制文字
    private String text;
    // 画布宽高
    private int width, height;
    private Paint paint;
    // 图片距离view顶部的距离
    private int paddingTop;
    // 有几个步骤
    private int stepCount;

    // 是否是第一步 第一步不需要 画左边线条
    private boolean mIsFirstStep;
    // 是否是最后一步 最后一步 不需要画右边线条
    private boolean mIsLastStep;

    public AuditProgressView(Context context) {
        this(context, null);
    }

    public AuditProgressView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AuditProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.AuditProgressView, defStyleAttr, 0);
        mIsCurrentComplete = array.getBoolean(R.styleable.AuditProgressView_apv_isCurrentComplete, false);
        mIsNextComplete = array.getBoolean(R.styleable.AuditProgressView_apv_isNextComplete, false);
        mIsFirstStep = array.getBoolean(R.styleable.AuditProgressView_apv_isFirstStep, false);
        mIsLastStep = array.getBoolean(R.styleable.AuditProgressView_apv_isLastStep, false);
        stepCount = array.getInteger(R.styleable.AuditProgressView_apv_stepCount, 2);
        text = array.getString(R.styleable.AuditProgressView_apv_text);
        array.recycle();

        paddingTop = dp2px(getContext(), 22);
        paint = new Paint();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(widthMeasureSpec);

        // 在宽高不是精确模式时,定义最小宽高

        if (widthMode != MeasureSpec.EXACTLY) {
            width = getDisplayMetrics(getContext()).widthPixels / stepCount;
        }

        if (heightMode != MeasureSpec.EXACTLY) {
            height = dp2px(getContext(), 90);
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 根据 当前步骤是否完成 确定中间的图片
        if (mIsCurrentComplete) {
            audit_drawBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ok);
        } else {
            audit_drawBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.notok);
        }

        // 获取自定义View的宽高
        width = getWidth();
        height = getHeight();

        // 绘制图片
        canvas.drawBitmap(audit_drawBitmap, width / 2 - audit_drawBitmap.getWidth() / 2, height / 2 - audit_drawBitmap.getHeight() / 2, paint);

        // 根据当前步骤是否完成 确定绘制文字颜色
        String mString = text;
        TextPaint tp = new TextPaint();
        if (mIsCurrentComplete) {
            tp.setColor(Color.parseColor("#000000"));
        } else {
            tp.setColor(Color.parseColor("#CCCCCC"));
        }

        // 绘制多行文字
        tp.setStyle(Paint.Style.FILL);
        Point point = new Point(width / 2, dp2px(getContext(), 70));
        tp.setTextSize(sp2px(getContext(), 14));
        textCenter(mString, tp, canvas, point, dp2px(getContext(), 57), Layout.Alignment.ALIGN_CENTER, 1, 0, false);

        // 绘制线条                                    //宽度
        paint.setStrokeWidth(dp2px(getContext(), 2));

        // 根据是不是第一个步骤 确定是否有左边线条
        if (!mIsFirstStep) {
            // 左边(线条颜色)
            // 根据当前步骤是否完成 来确定左边线条的颜色
            if (mIsCurrentComplete) {
                paint.setColor(Color.parseColor("#6CD89E"));
            } else {
                paint.setColor(Color.parseColor("#CCCCCC"));
            }                                                                                                              //距离进度点左右间距
            canvas.drawLine(0, height / 2, width / 2 - audit_drawBitmap.getWidth() / 2 - dp2px(getContext(), 0), height / 2, paint);
        }

        // 根据是不是最后的步骤 确定是否有右边线条
        if (!mIsLastStep) {
            // 右边(线条颜色)
            // 根据下一个步骤是否完成 来确定右边线条的颜色
            if (mIsNextComplete) {
                paint.setColor(Color.parseColor("#6CD89E"));
            } else {
                paint.setColor(Color.parseColor("#CCCCCC"));
            }                                                                                   //距离进度点左右间距
            canvas.drawLine(width / 2 + audit_drawBitmap.getWidth() / 2 + dp2px(getContext(), 0), height / 2, width, height / 2, paint);
        }
    }


    //绘制多行文字
    private void textCenter(String string, TextPaint textPaint, Canvas canvas, Point point, int width, Layout.Alignment align, float spacingmult, float spacingadd, boolean includepad) {
        StaticLayout staticLayout = new StaticLayout(string, textPaint, width, align, spacingmult, spacingadd, includepad);
        canvas.save();
        canvas.translate(-staticLayout.getWidth() / 2 + point.x, -staticLayout.getHeight() / 2 + point.y);
        staticLayout.draw(canvas);
        canvas.restore();
    }

    //当前已完成
    public void setIsCurrentComplete(boolean isCurrentComplete) {this.mIsCurrentComplete = isCurrentComplete;}

    //下一个是否已完成
    public void setIsNextComplete(boolean isNextComplete) {this.mIsNextComplete = isNextComplete;}

    //是否为第一步
    public void setIsFirstStep(boolean isFirstStep) {this.mIsFirstStep = isFirstStep;}

    //是否为最后一步
    public void setIsLastStep(boolean isLastStep) {this.mIsLastStep = isLastStep;}

    //显示内容
    public void setText(String text) {this.text = text;}

    //一屏幕宽度显示出来的总步数
    public void setStepCount(int stepCount) {this.stepCount = stepCount;}


    /**
     * 获取屏幕Metrics参数
     *
     * @param context
     * @return
     */
    public static DisplayMetrics getDisplayMetrics(Context context) {
        return context.getResources().getDisplayMetrics();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dpValue) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * density + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dp(Context context, float pxValue) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / density + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 sp
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 sp 的单位 转成为 px(像素)
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }
}

使用方法:

package com.p.h;

import android.os.Bundle;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.p.h.view.AuditProgressView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //绑定布局
        LinearLayout content = findViewById(R.id.ll_audit_content);

        //设置数据及状态
        content.addView(createView(5, true, true, true, false, "提交行程"));
        content.addView(createView(5, true, true, false, false, "支付费用"));
        content.addView(createView(5, true, true, false, false, "乘车出行"));
        content.addView(createView(5, false, false, false, true, "支付尾款"));
    }

    //初始化设置数据的方法
    public AuditProgressView createView(int stepCount, boolean isCurrentComplete, boolean isNextComplete, boolean isFirstStep, boolean isLastStep, String text) {
        AuditProgressView view = new AuditProgressView(this);
        view.setStepCount(stepCount);
        view.setIsCurrentComplete(isCurrentComplete);
        view.setIsNextComplete(isNextComplete);
        view.setIsFirstStep(isFirstStep);
        view.setIsLastStep(isLastStep);
        view.setText(text);
        return view;
    }
}

好啦,全部代码都在这了 每一步注释我都注释的特别清楚 这样应该可以看懂了吧 其实特别简单的 如果还有不懂的私信我...

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335