Filippo Fracascia
Filippo Fracascia

Reputation: 84

Using SpannableString with an EditText to change substring color

I'm trying to make a code editor in Android Studio. I'm kind of stuck when I need to change the color of a single keyword(like if, while, int etc.).

So far I've tried using SpannableString, but it doesn't seem to work for an EditText. The app runs and all, but as soon as I type if, it freezes and I have to restart. No logcat exceptions.

This is my code:

    EditText editText = findViewById(R.id.iftext);

    Keywords keys = new Keywords();

    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) {
            if(editText.getText().toString().contains(keys.iff())){

                String r = editText.getText().toString();
                int index = r.indexOf(editText.getText().toString().indexOf(keys.iff()));

                SpannableString spannableString = new SpannableString(r);
                spannableString.setSpan(new ForegroundColorSpan(Color.RED), index , index, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                editText.setText(spannableString);
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }

keys.iff() method only returns a string "if"

I wasn't sure about the index so I've tried with "0" and "1" constants and it still freezes.

Upvotes: 1

Views: 329

Answers (1)

Kishan Maurya
Kishan Maurya

Reputation: 3394

You have added TextWatcher to editText. So whenever you type or set chars for editText, it will notify in onTextChanged.

For first time, you type if keyword then code flow goes in inside if the condition.

editText.setText(spannableString); this line will again cause textWatcher to notify in onTextChanged. and it creates infinite loop. So Your app hangs or ANR.

Upvotes: 1

Related Questions