0

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 Answers2

1

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.

cutiko
  • 9,887
  • 3
  • 45
  • 59
  • Thank You ! It worked Perfectly. Just a small change instead of using the Spannable.Inclusive_EXCLUSIVE flag, you should use the Spannable.SPAN_EXCLUSIVE_INCLUSIVE flag, so that it starts making it BOLD / ITALIC from the current character. In case of Spannable.Inclusive_EXCLUSIVE, it makes the entire word BOLD / ITALIC. – Harikrishnan VK Apr 13 '20 at 17:31
  • then it should be `EXCLUSIVE_EXCLUSIVE` text length is 1 position more than the characters indexes, so it would be index out of bound – cutiko Apr 13 '20 at 20:01
  • Setting flag to EXCLUSIVE_EXCLUSIVE and SPAN_EXCLUSIVE_INCLUSIVE both are throwing the Exception. java.lang.IndexOutOfBoundsException: setSpan (35 ... 34) has end before start – Harikrishnan VK Apr 14 '20 at 07:18
  • Also, Could you tell me how to make the future text normal after user clicks the Normal Text Button? I tried the TypeFace.Normal option, but its not workng – Harikrishnan VK Apr 14 '20 at 12:09
  • You have to keep using spans `setSpans` or `removeSpans` spans are stackable you can have as many as you want to, read the article I share. – cutiko Apr 14 '20 at 13:26
-2

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)
Ronak Ukani
  • 603
  • 5
  • 20