项目中正好要用到这个功能。
- 先看效果
![](https://img.haomeiwen.com/i2062823/781aaaba4a5c1166.png)
说一下,6个格子这个有2种画法,一种就是直接画6个小格子,第二种就是先画外面的大矩形,里面在画5条竖线。我采取后者。一定要在xml设置 android:maxLength属性
/**
* 方格子密码控件
* Created by Admin on 2016/6/3.
*/
public class SquarePasswordView extends EditText {
/**
* 密码长度。通过在xml中的 android:maxLength 设置
*/
private int max;
private final Paint paint;
private int borderColor = Color.LTGRAY;
public SquarePasswordView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
//获得android:maxLength设置的值
max = UIUtils.getMaxLen(this);
if (max <1){
throw new IllegalArgumentException("android:maxLength < 1");
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (MeasureSpec.AT_MOST == widthMode) {
widthMeasureSpec = MeasureSpec.makeMeasureSpec(200, MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
//屏蔽长按时出现那个粘贴功能
@Override
public boolean onTouchEvent(MotionEvent event) {
return false;
}
@Override
protected void onDraw(Canvas canvas) {
//单个密码格子的宽度
int itemW = getMeasuredWidth() / max;
int itemH = getMeasuredHeight() / 2;
paint.setColor(borderColor);
paint.setStyle(Paint.Style.STROKE);
//先画外面的大矩形
canvas.drawRect(0, 0, getMeasuredWidth() - 1, getMeasuredHeight() - 1, paint);
//在画内部的几条竖线。
for (int i = 0; i < max - 1; i++) {
int x = itemW * (i + 1);
canvas.drawLine(x, 0, x, getMeasuredHeight()-1, paint);
}
//下面画圆形密码。每输入一个就画一个
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
int y = itemH;
int x = 0;
int radius = itemW / 6;
//根据输入的文本长度来画圆
for (int i = 0; i < getText().length(); i++) {
x = (itemW / 2) + i * itemW;
canvas.drawCircle(x, y, radius, paint);
}
}
}
网友评论