自定义看了很多学习自定义的文章和各位大神的例子,综合起来写了一个验证码控件来练手。
如果你对自定义控件还不够了解那么你可以先看鸿洋的这篇文章来学习基本的知识。
先来一张效果图
- 1.先自定义两个属性用来设置view的字体大小和验证码的个数。
<declare-styleable name="VerificationCodeView">
<attr name="textSize" format="dimension" />
<attr name="textCount" format="integer" />
</declare-styleable>
- 2.在代码中获取属性值
public VerificationCodeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.VerificationCodeView);
mTextSize = a.getDimensionPixelSize(R.styleable.VerificationCodeView_textSize, (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
mTextCount = a.getInt(R.styleable.VerificationCodeView_textCount, 4);
a.recycle();
}
在这里着重说明一点:用完TypedArray一定要记得 调用recycle()
方法释放资源
- 3.测量
@Override
protected void onMeasure(int widthMeasureSpec, int