Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Edittext Spannable Issue

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?

like image 445
Mert Serimer Avatar asked Dec 21 '14 18:12

Mert Serimer


1 Answers

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) { }
});
like image 68
matiash Avatar answered Oct 19 '22 18:10

matiash