How do you make a menuitem in android studio that makes text bold

Viewed 287

I am currently trying to create menuitem in my app that makes the highlighted text of an edittext bold when it's pressed. At the moment, the button works, but it removes the previous bold text every time the button is pressed.

Code for making text bold.

fun makeTextBold(editText: EditText) {
    val wholeText = editText.text.toString()
    val start = editText.selectionStart
    val end = editText.selectionEnd
    val ssb = SpannableStringBuilder(wholeText)

    ssb.setSpan(StyleSpan(Typeface.BOLD),start,end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    editText.text = ssb

}

Code for the menu item.

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        R.id.action_bold -> makeTextBold(characterNotesEditText)
    }
    return true
}

So if the text was currently like this

And I wanted to bold 'the text' as well as 'like this' it would change to:

So if the text was currently like this

Instead of:

So if the text was currently like this

I understand this is likely due to the fact I'm creating a new SpannableStringBuilder each time I click the button, but I'm struggling to find a solution to that issue - any help would be appreciated.

1 Answers

Call setSpan directly on editText.text instead of creating a new SpannableStringBuilder each time

fun makeTextBold(editText: EditText) {
    val wholeText = editText.text
    val start = editText.selectionStart
    val end = editText.selectionEnd

    wholeText.setSpan(StyleSpan(Typeface.BOLD),start,end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
Related