Maharshi
Maharshi

Reputation: 146

Is there a way I can change the text color of an editText on encountering a word from a string array?

I am trying to implement something similar to a code editor where keywords are automatically highlighted. I am going to have a string array and I want to change the color and font of the editText string when the user types the text and it matches a string from the string array. I am using the addTextChangeListener but the text of the whole editText changes. I want just the matched word to be highlighted. Here is my code:

inputCodeEditText.addTextChangedListener(new TextWatcher() {
        @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) {
            if (s.toString().contains("for"))
            {
                inputCodeEditText.setTextColor(getResources().getColor(R.color.indigo));
            }
        }
    });

I understand I have to use spans but the code crashes. Can anyone help me with the correct usage of spannable strings with addTextChangedListener() ? 

Upvotes: 0

Views: 53

Answers (1)

Kozmotronik
Kozmotronik

Reputation: 2520

Use addTextChangeListener API eg:

editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // The changed text comes in "s" parameter.
                // Here you can watch the changes and take an action you want...
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

Upvotes: 1

Related Questions