Android Edittext Spannable Issue

Everytime Edittext onAfterTextChange method, I check if some special string is entered (which comes from the functionlist variable), and then change this special color. Code below

for(String s:functionList) { final Pattern p = Pattern.compile(s); final Matcher matcher = p.matcher(inputStr); while(matcher.find()) { //if(matcher.end() - matcher.start()== s.length()) inputStr.setSpan(new ForegroundColorSpan(Color.parseColor(highlightColor)), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } 

The reason I am not using the Html.FromHtml method; this forces me to use the setText method, which changes the cursor position, and since my edittext is also changed from buttons (call settext buttons) not only to softkeyboard, this settext method destroys the cursor position, since the button changes the cursor position to 0 EVEN IS NOT !! !! so I cannot add something in the middle using softkeyboard (when I try to add, the cursor position is always set to 0). That is why I have to use spannable.

In any case, my problem is that one of my special texts is the "magazine". When I enter the log, it works fine ( log ), when a log with a space character is added ( log log ), it works fine again , but WHEN I DELETE G from the second log, the first color of the log also disappeared !!! (log lo), which should not happen. Think bold journal as it is colored ...

Why is this happening?

+5
source share
1 answer

If I understand correctly what you are trying to do, you should try something like:

 edit.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { Spannable inputStr = (Spannable)s; for (String function : functionList) { for (ForegroundColorSpan old : inputStr.getSpans(start, inputStr.length(), ForegroundColorSpan.class)) inputStr.removeSpan(old); final Pattern p = Pattern.compile(function); final Matcher matcher = p.matcher(inputStr); while (matcher.find()) inputStr.setSpan(new ForegroundColorSpan(Color.BLUE), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); 
0
source

Source: https://habr.com/ru/post/1209667/


All Articles