Android Edittext Spannable Issue

3.9k views Asked by At

Everytime Edittext onAfterTextChange method, i check if some special string(which comes from functionlist variable) is entered then change that string's special color. Code is 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 why i am not using Html.FromHtml method is; it forces me to use setText method which changes cursor position and since my edittext is also changed from buttons(buttons call settext) not only softkeyboard, that settext method ruins cursor position since button changes sets cursor position to 0 EVEN IT IS NOT!!!! thus i cannot add something in the middle with softkeyboard(when i try to add, cursorposition is set always to 0). This is why i have to use spannable.

Anyway my problem is, for example one of my special text is "log".. when i input log it works fine(log), when append log with space character(log log) it works fine again but WHEN I REMOVE g from second log, the first log color is also gone!!!(log lo) which must not supposed to be happen. Think bold logs as it is colored...

Why is it happening?

1

There are 1 answers

0
matiash On BEST ANSWER

If I understand correctly what you're attempting 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) { }
});