i am trying to create a basic text editor. I almost achived what i wanted to do but there are some problems. When i press 'B' button, it makes text bold. If i keep writing without giving space and press 'B' button again, all letters i write turn normal. But i want to keep letters bold which are already bold. When i give space, it works as i want, makes bold, italic or normal. Here are some parts of my code:
editor.textChangedListener {
beforeTextChanged { _, _, _, _ ->
val length = editor.text?.length
length?.let {
if (it > 0) {
val styleSpan = when {
isBold && isItalic -> StyleSpan(Typeface.BOLD_ITALIC)
isBold && !isItalic -> StyleSpan(Typeface.BOLD)
!isBold && isItalic -> StyleSpan(Typeface.ITALIC)
else -> StyleSpan(Typeface.NORMAL)
}
val spannable = Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
if (it < start) start = 0
editor.text?.setSpan(styleSpan, start, it, spannable)
}
}
}
}
boldButton.onClick {
isBold = !isBold
val image = when (isBold) {
true -> R.drawable.ic_bold_active
false -> R.drawable.ic_bold
}
start = editor.text!!.length
boldButton.setImageResource(image)
}