Android 实现仿支付宝的密码均分输入框
Android仿支付宝的密码均分输入框
此为安卓项目,通过重绘edittext进行文字的均分排布。
直接贴上代码:
packagecom.xxx.xxx;
importandroid.content.Context;
importandroid.graphics.Canvas;
importandroid.graphics.Color;
importandroid.graphics.Paint;
importandroid.graphics.Rect;
importandroid.text.Editable;
importandroid.text.Selection;
importandroid.text.TextWatcher;
importandroid.util.AttributeSet;
importandroid.view.ViewGroup;
importandroid.widget.EditText;
/**
*此控件为均分输入框控件
*使用说明:XML文件中设置好文字大小,设置好宽度。高度使用wrap_content更佳,亦可设置固定高度
*(随着输入的行数变化会导致高度成倍增加)
*允许设置每行显示的文字个数
*允许设置最多显示多少行
*允许设置密码符显示
*允许设置多行输入
*
*Createdbyyueeron2015/10/22.
*/
publicclassExcelEditViewextendsEditText{
privateintmMaxLength=6;//一行显示的最大字符数
privateintmColorId=Color.BLACK;//字体颜色
privatebooleanisPassword=false;//是否需要显示密码符
privatefloatmHeight=0.0f;//默认情况的高度
privateintmMaxLine=0;//最大的行数:如果为0,---表示支持多行输入不为0,--则为该行
publicExcelEditView(Contextcontext){
super(context);
init();
}
publicExcelEditView(Contextcontext,AttributeSetset){
super(context,set);
init();
}
privatevoidinit(){
this.addTextChangedListener(newTextWatcher(){
@Override
publicvoidbeforeTextChanged(CharSequences,intstart,intcount,intafter){
}
@Override
publicvoidonTextChanged(CharSequences,intstart,intbefore,intcount){
//TODOAuto-generatedmethodstub
Editableeditable=ExcelEditView.this.getText();
intlen=editable.length();
if(mMaxLine>0&&len>mMaxLength*mMaxLine)
{
intselEndIndex=Selection.getSelectionEnd(editable);
Stringstr=editable.toString();
StringnewStr=str.substring(0,mMaxLength*mMaxLine);
ExcelEditView.this.setText(newStr);
editable=ExcelEditView.this.getText();
//新字符串的长度
intnewLen=editable.length();
//旧光标位置超过字符串长度
if(selEndIndex>newLen)
{
selEndIndex=editable.length();
}
//设置新光标所在的位置
Selection.setSelection(editable,selEndIndex);
}
}
@Override
publicvoidafterTextChanged(Editables){
}
});
}
publicvoidsetIsPassword(booleanisPassword){
this.isPassword=isPassword;
}
publicvoidsetmMaxLine(intline){
this.mMaxLine=line;
}
publicvoidsetmMaxLength(intleng){
this.mMaxLength=leng;
}
@Override
publicvoidsetTextColor(intcolor){
super.setTextColor(color);
mColorId=color;
}
@Override
protectedvoidonDraw(Canvascanvas){
char[]txt=this.getText().toString().toCharArray();//取出字符数组
inttxtLine=getLineFromCharArray(txt);//计算有多少行
if(mMaxLine>0&&txtLine>mMaxLine){//进行行数的上限处理
txtLine=mMaxLine;
}
if(this.isPassword){//密码符的转义
for(inti=0;i(i+line*mMaxLength);i++){
canvas.drawText(String.valueOf(txt[i+line*mMaxLength]),(i+1)*per-textWidth,perHeight*(line+1)+textHeight/2,countPaint);//进行绘制
}
}
}
privateintgetLineFromCharArray(char[]txt){
intline=((txt.length-1)/mMaxLength)+1;
returnline;
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!