How can I workaround this android TextWatcher restriction? -
i have textwatcher
defined on edittext
field. within textwatcher.ontextchanged()
method, reset edittext
value empty string. when
java.lang.indexoutofboundsexception: setspan (2 ... 3) ends beyond length 0 @ android.text.spannablestringbuilder.checkrange(spannablestringbuilder.java:934)
can suggest workaround safely clear down edittext within textwatcher.
my code ...
textwatcher tw = new textwatcher() { public void ontextchanged (charsequence chars, int start, int before,int count) { // if user keys enter, process contents , clear down edittext if (chars.tostring().indexof("\n") > -1) { processchars(s.tostring().replace("\n", "")); edittextfield.settext(""); } } }; edittextfield.addtextchangedlistener(tw);
as @pskink has mentioned in comments, "it error attempt make changes s this callback". so, instead of changing edittext
value directly, use handler
. example provided below reference.
private edittext medittext; private textwatcher mtextwatcher; private static final int msg_add_textwatcher = 100; private static final int msg_process_chars = 200; private static final int msg_remove_textwatcher = 300; private final myhandler mhandler = new myhandler(this); private static class myhandler extends handler { private final weakreference<mainactivity> myactivity; public myhandler(mainactivity activity) { myactivity = new weakreference<mainactivity>(activity); } @override public void handlemessage(message msg) { mainactivity activity = myactivity.get(); if (activity != null) { switch (msg.what) { case msg_add_textwatcher: activity.addtextwatcher(); break; case msg_process_chars: activity.processchars(msg.obj.tostring()); break; case msg_remove_textwatcher: activity.removetextwatcher(); break; default: super.handlemessage(msg); } } } } ... @override public void ontextchanged(charsequence s, int start, int before, int count) { if (s.tostring().indexof("\n") > -1) { message msg = new message(); msg.what = msg_process_chars; msg.obj = s.tostring().replace("\n", ""); mhandler.sendmessage(msg); } } ... private void addtextwatcher() { medittext.addtextchangedlistener(mtextwatcher); } private void removetextwatcher() { medittext.removetextchangedlistener(mtextwatcher); medittext.settext(""); } private void processchars(string msg) { toast.maketext(this, msg, toast.length_short).show(); mhandler.sendemptymessage(msg_remove_textwatcher); }
you need call mhandler.sendemptymessage(msg_add_textwatcher);
where/whenever appropriate according project requirements.
Comments
Post a Comment