Charm
Charm

Reputation: 51

Changing the text color of specific word when I type in the edittext

I want to change the color of the specific word that I typed in edittext. but this code only change the word once. When I type another function it doesn't change the color.

tt.addTextChangedListener(new TextWatcher() {
            final String FUNCTION = "function";
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                int index = s.toString().indexOf(FUNCTION);
                if (index >= 0) {
                    s.setSpan(
                            new ForegroundColorSpan(Color.GREEN),
                            index,
                            index + FUNCTION.length(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
        });

Upvotes: 4

Views: 653

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

indexOf will always give the index of first found value so you need to loop through your string and find all the function string and apply span on it and to search from specific index use indexOf (String str, int fromIndex)

// a single object to apply on all strings 
ForegroundColorSpan fcs = new ForegroundColorSpan( Color.GREEN);    
String s1 = s.toString();
int in=0; // start searching from 0 index

// keeps on searching unless there is no more function string found 
while ((in = s1.indexOf(FUNCTION,in)) >= 0) {
    s.setSpan(
        fcs,
        in,
        in + FUNCTION.length(),
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    // update the index for next search with length
    in += FUNCTION.length();
}

To avoid matching div from divide you need to use regex \\b where \\b mean word boundary to avoid matching div with divide

ForegroundColorSpan fcs = new ForegroundColorSpan( Color.GREEN);    
String s1 = s.toString();

Pattern pattern = Pattern.compile("\\b"+FUNCTION+"\\b");
Matcher matcher = pattern.matcher(s1);

// keeps on searching unless there is no more function string found 
while (matcher.find()) {
    s.setSpan(
            fcs,
            matcher.start(),
            matcher.end(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

Upvotes: 5

Related Questions