android - Want to format the number in EditText -
i want format input in form of number in edittext.the format 01-133134-124. wanted first - after 2 number next dash after 6 numbers.i tried whenever pressed delete/backspace because of wrong entry format stopped working , no dash placed after input of 2 number or 6 numbers.here code.where enrollement edittext field.
format : 2digitnumber-6dignumber-3dignumber
enrollement.addtextchangedlistener(new textwatcher() { @override public void ontextchanged(charsequence s, int start, int before, int count) { enrollement.setonkeylistener(new view.onkeylistener() { @override public boolean onkey(view v, int keycode, keyevent event) { if (keycode == keyevent.keycode_del) keydel = 1; return false; } }); if (keydel == 0) { int len = enrollement.gettext().length(); if (len == 2) { int leng = enrollement.gettext().length(); if(leng==2) { enrollement.settext(enrollement.gettext() + "-"); enrollement.setselection(enrollement.gettext().length()); } } else if (len == 9) { int leng = enrollement.gettext().length(); if(leng==9) { enrollement.settext(enrollement.gettext() + "-"); enrollement.setselection(enrollement.gettext().length()); } } } else { keydel = 0; } } @override public void aftertextchanged(editable arg0) { } @override public void beforetextchanged(charsequence arg0, int arg1, int arg2, int arg3) { } });
it easier if changed approach bit. analyzing unformatted verion of string after every single change in edittext
.
try (remember set android:maxlength="13"
edittext
):
enrollement.addtextchangedlistener(new textwatcher() { final int[] blocklengths = new int[]{2, 6, 3}; string munformatted = ""; @override public void ontextchanged (charsequence s,int start, int before, int count){ string unformattedseq = s.tostring().replace("-", ""); if (munformatted.length() == unformattedseq.length()) { return; //length of text has not changed } munformatted = unformattedseq; //formatting sequence stringbuilder formatted = new stringbuilder(); int blockindex = 0; int currentblock = 0; (int = 0; < munformatted.length(); ++i) { if (currentblock == blocklengths[blockindex]) { formatted.append("-"); currentblock = 0; blockindex++; } formatted.append(munformatted.charat(i)); currentblock++; } enrollement.settext(formatted.tostring()); enrollement.setselection(formatted.length()); } @override public void beforetextchanged (charsequence s,int start, int count, int after){ } @override public void aftertextchanged (editable s){ } });
this code should work correctly. improve setselection
part (currently if delete number in middle of edittext
move cursor end of text).
Comments
Post a Comment