欢迎来到“实现自定义密码输入控件”这一章节,PasswordInputView定义了密码输入的监听,支持直接在布局文件定义属性值,支持直接获取密码输入的长度,原始密码……
<强>先上图强>
<强> PasswordInputView是做什么的& # 63;强>
PasswordInputView是一个自定义密码输入的控件,类似支付宝,微信支付的密码输入,同时定义了密码输入的监听,支持直接在布局文件定义属性值,支持直接获取密码输入的长度,原始密码等,还可以扩展其他方法,请自行实现。
<>强实现原理强>
1。创建一个类“PasswordInputView”,让其继承EditText,因为我们要实现的自定义的观点是用来密码输入的,所以必须继承EditText。
2。为了在布局(布局)文件(xml)能直接定义PasswordInputView各个属性的值,我们需要定义PasswordInputView带AttributeSet参数的构造方法。
公共PasswordInputView(上下文语境,AttributeSet attr) { 超级(上下文,attr); init(上下文,attr); }
3。在“价值/attrs.xml’中定义PasswordInputView各个属性及其类型,如:
& lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比; & lt; resources> & lt; declare-styleable name=" Passwordinputview比; & lt; attr name==罢?皃asswordLength”格式比; & lt; attr=name=" borderWidth "格式"维度"/比; & lt; attr name==拔取?癰orderRadius”格式比; & lt; attr name==把丈?癰orderColor”格式比; & lt; attr=name=" passwordWidth "格式"维度"/比; & lt; attr name==把丈?皃asswordColor”格式比; & lt;/declare-styleable> & lt;/resources>
4。重载OnDraw(帆布画布)方法,并在其实现画边框,画内容区域(以填充模式绘制Paint.Style.FILL),画分割线,画实心圆点(密码)。有人可能会问:画了边框,分割线,就可以了,为什么还要画内容区域?问得好,笔者在实现过程中也碰到这个问题,当时没有画内容区域,导致输入的原始内容也显示出来了<强>(如下异常图),所以画内容区域(以填充模式绘制Paint.Style.FILL)是为了掩盖原始内容不被发现,切记必不可少。强>
正确代码如下:
私人空间初始化上下文语境,AttributeSet attr () { TypedArray ta=上下文。obtainStyledAttributes (attr, R.styleable.Passwordinputview); 尝试{ passwordLength=ta.getInt (R.styleable。Passwordinputview_passwordLength passwordLength); borderWidth=ta.getDimensionPixelSize (R.styleable。Passwordinputview_borderWidth borderWidth); borderRadius=ta.getDimensionPixelSize (R.styleable。Passwordinputview_borderRadius borderRadius); borderColor=ta.getColor (R.styleable。Passwordinputview_borderColor borderColor); passwordWidth=ta.getDimensionPixelSize (R.styleable。Passwordinputview_passwordWidth passwordWidth); passwordColor=ta.getColor (R.styleable。Passwordinputview_passwordColor passwordColor); }捕捉(异常e) { } ta.recycle (); borderPaint=new油漆(); borderPaint.setAntiAlias(真正的); borderPaint.setColor (borderColor); borderPaint.setStrokeWidth (borderWidth); borderPaint.setStyle (Paint.Style.FILL);//以填充模式来画,防止原始输入内容显示出来 passwordPaint=new油漆(); passwordPaint.setAntiAlias(真正的); passwordPaint.setColor (passwordColor); passwordPaint.setStrokeWidth (passwordWidth); } @Override 保护空白> 公共空间setBorderWidth (int borderWidth) { 这一点。borderWidth=borderWidth; borderPaint.setStrokeWidth (borderWidth); postInvalidate (); }
<强>动态图强>
<强>项目源码强>
点此链接
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。