Referring to the original question you mention in this question and assuming that you are using the "DottedUnderlineSpan" from the original question, you will need to make the following changes:
The annotation spans are replaced with ReplacementSpans which must be explicitly recomputed ince you are handling orientation changes yourself. Once the annotation spans are set, do not remove them. They will remain valid across orientation changes.
The ReplacementSpans will, however, need to change. Upon orientation change, remove the replacement spans, allow layout to proceed and then recalculate the ReplacementSpans as shown in the following code and that should do it.
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
val textView1 = findViewById<TextView>(R.id.textView1)
removeUnderlineSpans(textView1)
textView1.viewTreeObserver.addOnPreDrawListener(
object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
textView1.viewTreeObserver.removeOnPreDrawListener(this)
replaceAnnotations(textView1)
return false
}
}
)
}
private fun removeUnderlineSpans(textView: TextView) {
val text = textView.text as Spannable
val spans = text.getSpans(0, text.length, DottedUnderlineSpan::class.java)
spans.forEach { span ->
text.removeSpan(span)
}
textView.setText(text, TextView.BufferType.SPANNABLE)
}
private fun replaceAnnotations(textView: TextView) {
val text = SpannableString(textView.text)
val spans =
text.getSpans(0, text.length, Annotation::class.java).filter { span ->
span.key == ANNOTATION_FOR_UNDERLINE
}
if (spans.isNotEmpty()) {
val layout = textView.layout
spans.forEach { span ->
replaceAnnotationSpan(text, span, layout)
}
textView.setText(text, TextView.BufferType.SPANNABLE)
}
}