自定义密码输入框(passwordEditText)
项目中需要一个自定义的密码输入框,在网上找了许多案例,但是就是闲代码太多或者长得不好看,于是就自己动手封装了一个密码输入框。
感谢http://www.jianshu.com/p/a8cfe904f55a提供的部分思路
应用场景:activity或者fragment(需要输入支付密码或者短信验证码的地方)
首先我先定义一个公式(密码输入框[s],宽度[w],密码长度[l],间距[m])
s.w=l*w+m(l+1) [即密码框的宽度=密码个数X单个框的宽度+间距X加一的密码个数]*
代码分析
1、需求的参数定义
/**
* 密码信息
*/
private int length; //密码个数
private boolean showPsd; //是否显示明文密码
private int margin; //间距
private int txtSize; //字体大小
private int txtColor; //字体颜色
private StringBuilder txt; //输入的信息
private Paint textPaint; //文字的画笔
private Rect txtRect; //文字矩形信息
/**
* 密码框信息
*/
private int rectStroke; //密码框宽度
private int rectNumberColor; //默认框颜色
private int rectChooseColor; //选中框颜色
private Paint rectPaint; //矩形框的画笔
private Paint circlePaint; //圆形画笔
private List<Rect> list; //矩形框集合
private OnInputCompleteListener onInputCompleteListener; //回调接口
这里主要定义的是该控件中需要用到的参数
2、参数的初始化
/**
* 初始化参数和设置键盘自动弹出时间
*/
private void init() {
rectPaint = new Paint();
textPaint = new Paint();
circlePaint = new Paint();
txtRect = new Rect();
txt = new StringBuilder();
list = new ArrayList<>();
setBackgroundDrawable(null);
setLongClickable(false);
setTextIsSelectable(false);
setCursorVisible(false);
//自动弹出软键盘
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
InputMethodManager inputManager =
(InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(PsdInputBox.this, 0);
}
}, 400);
}
/**
* 初始化配置信息
* @param context
* @param attrs
*/
private void initAttrs(Context context, AttributeSet attrs) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.PsdInputBox);
txtColor = ta.getColor(R.styleable.PsdInputBox_txtColor, Color.BLUE);
rectNumberColor = ta.getColor(R.styleable.PsdInputBox_rectNumberColor, Color.GRAY);
rectChooseColor = ta.getColor(R.styleable.PsdInputBox_rectChooseColor, Color.BLUE);
txtSize = sp2px(context, ta.getDimension(R.styleable.PsdInputBox_txtSize, 14));
margin = dip2px(context, ta.getDimension(R.styleable.PsdInputBox_margin, 5));
rectStroke = dip2px(context, ta.getDimension(R.styleable.PsdInputBox_rectStroke, 40));
length = ta.getInteger(R.styleable.PsdInputBox_length, 6);
showPsd = ta.getBoolean(R.styleable.PsdInputBox_showPsd, false);
ta.recycle();
}
熟悉自定义控件的朋友都知道我们有些在配置文件中的参数需要在这里进行初始化,附上配置文件代码:
<!--自定义支付框-->
<declare-styleable name="PsdInputBox">
<!--外边框颜色-->
<attr name="rectNumberColor" format="color" />
<!--外边框选中的颜色-->
<attr name="rectChooseColor" format="color" />
<!--内容文字的颜色-->
<attr name="txtColor" format="color" />
<!--内容文字的大小-->
<
自定义密码输入框实现详解

本文介绍如何自定义一个密码输入框(passwordEditText),适用于支付密码或短信验证码输入场景。通过参数定义、初始化、重写onMeasure和onDraw方法,以及监听键盘事件,实现了简洁的密码输入框功能。
最低0.47元/天 解锁文章
3788

被折叠的 条评论
为什么被折叠?



