前言
本篇文章主要是实现仿QQ步数View,很老的一个View了,但技术永不落后,开搂!
最终效果如下:
1. 结构分析
QQStepView
主要由三个元素组成:
- 显示一个圆环进度条,通过外环和内环的角度变化来表示进度。
- 支持自定义外环颜色、内环颜色、进度文本颜色和文本大小,这些都可以通过 XML 属性来配置。
- 支持动态更新进度,通过方法
setStep(int step)
可以更新当前进度。
2. 定义自定义属性
为了使该控件在 XML 布局文件中可配置,我们需要定义一些自定义属性,例如外圈颜色、内圈颜色、边框宽度、文本大小和文本颜色。这些属性可以通过 res/values/attrs.xml
文件来定义:
<declare-styleable name="QQStepView">
<attr name="outerColor" format="color" />
<attr name="innerColor" format="color" />
<attr name="borderWidth" format="dimension" />
<attr name="stepTextSize" format="dimension" />
<attr name="stepTextColor" format="color" />
</declare-styleable>
3. 初始化视图元素
通过 TypedArray 获取用户在 XML 中设置的属性。
public QQStepView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.QQStepView);
mOuterColor = array.getColor(R.styleable.QQStepView_outerColor, mOuterColor);
mInnerColor = array.getColor(R.styleable.QQStepView_innerColor, mInnerColor);
mBorderWidth = array.getDimensionPixelSize(R.styleable.QQStepView_borderWidth, mBorderWidth);
mStepTextSize = array.getDimensionPixelSize(R.styleable.QQStepView_stepTextSize, mStepTextSize);
mStepTextColor = array.getColor(R.styleable.QQStepView_stepTextColor, mStepTextColor);
array.recycle();
}
初始化画笔(Paint)
mOuterPaint = new Paint();
mOuterPaint.setColor(mOuterColor);
mOuterPaint.setAntiAlias(true);
mOuterPaint.setStyle(Paint.Style.STROKE); // 实心
mOuterPaint.setStrokeWidth(mBorderWidth);
mOuterPaint.setStrokeCap(Paint.Cap.ROUND);
mInnerPaint = new Paint();
mInnerPaint.setColor(mInnerColor);
mInnerPaint