android addTextChangedListener(TextWatcher) not working for the second time -
i have 6 edit texts on screen (used enter 6 digits) if enter 1 digit on 1 edittext field focus should go onto next 1 , on. if hit space on edit text field focus should come previous edittext field
for used below code
edittext2.addtextchangedlistener(new textwatcher() { public void ontextchanged(charsequence s, int start, int before, int count) { if (edittext2.gettext().tostring().length() == 1) { edittext3.requestfocus(); } else if (edittext2.gettext().tostring().length() == 0) { edittext1.requestfocus(); } } public void beforetextchanged(charsequence s, int start, int count, int after) { } public void aftertextchanged(editable s) { } });
normally , ontextchange listener works if don't hit backspace on of edit texts. if hit backspace on edittext2 , land on edittext1(some value on present) , try enter on it. cursor not going edittext2 addtextchangedlistener not working.
any appreciated.
i'm assuming you've set edittext
fields maxlength
of 1. this:
<edittext android:id="@+id/edit_text_one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxlength="1" android:inputtype="number" android:digits="0123456789" />
when maxlength
set 1, textwatcher
not triggered when trying enter additional characters. 1 way solve problem when moving backwards use edittext.setselection(0, edittext.length());
see below working example:
final list<edittext> fields = new arraylist<>(); fields.add((edittext) findviewbyid(r.id.edit_text_one)); fields.add((edittext) findviewbyid(r.id.edit_text_two)); fields.add((edittext) findviewbyid(r.id.edit_text_three)); fields.add((edittext) findviewbyid(r.id.edit_text_four)); fields.add((edittext) findviewbyid(r.id.edit_text_five)); fields.add((edittext) findviewbyid(r.id.edit_text_six)); (edittext edittext : fields) { edittext.addtextchangedlistener(new textwatcher() { @override public void beforetextchanged(charsequence charsequence, int start, int count, int after) {} @override public void ontextchanged(charsequence charsequence, int start, int count, int after) { (int = 0; < fields.size(); i++) { // determine 1 of fields focused if (fields.get(i).hasfocus()) { if (charsequence.length() == 1) { // if focused field has character in it, move next field if (fields.size() > + 1) { edittext nextfield = fields.get(i + 1); nextfield.requestfocus(); } } else if (charsequence.length() == 0) { // if focused field deleted, move previous field if (i - 1 >= 0) { edittext prevfield = fields.get(i - 1); prevfield.requestfocus(); // select text replaced when pressing button prevfield.setselection(0, prevfield.gettext().length()); } } break; } } } @override public void aftertextchanged(editable editable) {} }); }
Comments
Post a Comment