Using Spannable for full EditText in Android

I have an EditText View which is being used to make users enter a text. After certain characters, I want to reduce the Font Size of the Text within the EditText. I am using the TextWatcher's onTextChanged listener to track the user input and the length of the characters. This part is working as expected. But to set the Font size of the text I am using the below approach:

final Spannable span = new SpannableString(editText.getText());
span.setSpan(new RelativeSizeSpan(0.9f), 0, string.length), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Now, I am facing two problems:

  1. The current text size gets changed as desired but if the user enters new text in front of the current text then the size of that new text is not the same as the desired updated text font size but is same as the original EditText Text font size.

For eg., if the current text is “ABC” and then the font size of this text is updated then if a user enters “123” in front of “ABC” like “123ABC” the size of 123 is not the same as updated text size but is the same as the original font size but the “ABC” continues to remain the updated desired font size.

  1. The cursor of the EditText always moves to the start. I want the cursor position to be at the same position as it was before updating the text size.

Any help would be appreciated.



Check this, Easy to implement and can solve lot of the issues we face related to SpannableString