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.