1.说明
这篇文章主要就是讲解下,在自定义View中的第三个构造方法中获取自定义View的自定义属性。下边请看详细内容。
2. 获取自定义属性
2.1 attrs.xml资源文件如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 自定义属性 -->
<declare-styleable name="QQStepView">
<attr name="outerColor" format="color"/>
<attr name="innerColor" format="color"/>
<attr name="borderWidth" format="dimension"/>
<attr name="stepTextColor" format="color"/>
<attr name="stepTextSize" format="dimension"/>
</declare-styleable>
</resources>
2.2 在自定义View的构造方法中获取自定义属性如下
public QQStepView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// 1. 创建attrs.xml文件,编写自定义属性
// 2. 在布局中使用
// 3. 在自定义View中获取自定义属性
// 4. 测量onMeasure()
// 5. 绘制固定圆弧、变化圆弧、文字
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.QQStepView);
mOurterColor = array.getColor(R.styleable.QQStepView_outerColor , mOurterColor) ;
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) ;
// 圆弧的宽度
mRoundWidth = (int)array.getDimension(R.styleable.ProgressBar_roundWidth , dip2px(10)) ;
// 字体大小
mProgressTextSize = array.getDimensionPixelSize(R.styleable.ProgressBar_progressTextSize , sp2px(mProgressTextSize)) ;
array.recycle();
// 外圆弧画笔
mOuterPaint = new Paint() ;
mOuterPaint.setAntiAlias(true);
mOuterPaint.setStrokeWidth(mBorderWidth);
mOuterPaint.setColor(mOurterColor);
mOuterPaint.setStrokeCap(Paint.Cap.ROUND);
mOuterPaint.setStyle(Paint.Style.STROKE); //画笔空心
// 内圆弧画笔
mInnerPaint = new Paint() ;
mInnerPaint.setAntiAlias(true);
mInnerPaint.setStrokeWidth(mBorderWidth);
mInnerPaint.setColor(mInnerColor);
mInnerPaint.setStrokeCap(Paint.Cap.ROUND);
mInnerPaint.setStyle(Paint.Style.STROKE); //画笔空心
// 文字画笔
mTextPaint = new Paint() ;
mTextPaint.setAntiAlias(true);
mTextPaint.setColor(mStepTextColor);
mTextPaint.setTextSize(mStepTextSize);
}
private int sp2px(float sp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics());
}
private float dip2px(int dip) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, getResources().getDisplayMetrics());
}