Android - Set EditText Bold / Italic / Underline for the future text

1.4k Views Asked by At

I want to apply the Text Formatting Options to the EditText. I am able to apply all the formating such as Bold, Italic, Underline, Strike-Through, BulletPoint when the text is selected. But, I want to apply the formatting to the future text that the user will type.

I used the mEditText.setTypeface(null, Typeface.BOLD) / mEditText.setTypeface(null, Typeface.ITATIC), but it makes entire EditText Bold / Italic.

I want to make it Bold / Italic only to the text that will be typed after Bold / Italic button is clicked.

There are some similar questions but none of them have the answers to it.

2

There are 2 best solutions below

5
cutiko On BEST ANSWER

You need to use spans.

editText.doAfterTextChanged() {...
        when(selectedStyle) {
               Italic -> {
                      val spannable = SpannableString(text)
                      spannable.setSpan(Spans.Italic, styleStart, text.length, Spannable.EXCLUSIVE_EXCLUSIVE)
                }
         }
}

This article should help you https://medium.com/androiddevelopers/spantastic-text-styling-with-spans-17b0c16b4568

And this question should help you with the text listener android on Text Change Listener

When the user press the button for changing the style then save the text lenght so in the TextWatcher after the text change you apply the style selected.

Maybe you should consider looking for some WYSIWYG library around.

0
Ronak Ukani On

For only Bold :

editText.setTypeface(Typeface.DEFAULT,Typeface.BOLD)

For only Italic :

editText.setTypeface(Typeface.DEFAULT,Typeface.ITALIC)

For Bold and Italic Both,

editText.setTypeface(Typeface.DEFAULT,Typeface.BOLD_ITALIC)