Android自定义View之审核进度条

作者: i小灰 | 来源:发表于2020-08-19 19:27 被阅读0次
概述:
在做商城类的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;
    }
}

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

相关文章

网友评论

    本文标题:Android自定义View之审核进度条

    本文链接:https://www.haomeiwen.com/subject/uiudjktx.html