android - Change the colour of text as the user types hash tags -
i working on application user can post content feed. in edit text (used composing) text colour grey. when user types hash tag e.g. #help need colour text black type, when user types '#' text must coloured black until start new word, text colour needs revert grey.
i have been trying using text watcher , spannable string colour.
here have done textwatcher ontextchanged
@override public void ontextchanged(charsequence s, int start, int before, int count) { //remove text watcher prevent infinite mtextfield.removetextchangedlistener(contentfieldwatcher); string startchar = null; startchar = character.tostring(s.charat(start)); l.i(getclass().getsimplename(), "character of new word: " + startchar); if (startchar.equals("#")) { tagcheck(s.tostring().substring(start), start, start + count); } }
tagcheck method
private void tagcheck(string s, int start, int end) { mspannable.setspan(new foregroundcolorspan(getresources().getcolor(r.color.black_colour)), start, end, spanned.span_exclusive_exclusive); }
mspannable spannable.
the problem method '#' shows startchar, when user types next character, either symbol or letter, shows startchar. if user typed santa - 's' remains startchar. issue i'm facing how dynamically colour text user types hashtag.
so plain letters work correctly, when use symbol not. hope question has clarity..i've been looking @ few days , it's getting hazy :)
i tried , found soloution
you can use following code
spannable mspanable; int hashtagiscoming = 0; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); final edittext edt = (edittext) findviewbyid(r.id.edittext1); mspanable = edt.gettext(); edt.addtextchangedlistener(new textwatcher() { @override public void ontextchanged(charsequence s, int start, int before, int count) { string startchar = null; try{ startchar = character.tostring(s.charat(start)); log.i(getclass().getsimplename(), "character of new word: " + startchar); } catch(exception ex){ startchar = " "; } if (startchar.equals("#")) { tagcheck(s.tostring().substring(start), start, start + count); hashtagiscoming++; } if(startchar.equals(" ")){ hashtagiscoming = 0; } if(hashtagiscoming != 0) { tagcheck(s.tostring().substring(start), start, start + count); hashtagiscoming++; } } @override public void beforetextchanged(charsequence s, int start, int count, int after) { // todo auto-generated method stub } @override public void aftertextchanged(editable s) { // todo auto-generated method stub } }); } private void tagcheck(string s, int start, int end) { mspanable.setspan(new foregroundcolorspan(getresources().getcolor(r.color.color)), start, end, spanned.span_exclusive_exclusive); }
Comments
Post a Comment