0

I have done the the multi line text support from below link Dotted underline TextView not wrapping to the next line using SpannableString in Android

After changing the orientation portrait to landscape dotted underline moved to other position

I have added 'android:configChanges="orientation"' in manifest for prevent on create call.

    <activity android:name=".Main2Activity"
        android:configChanges="orientation">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


setAnnotation(
                spannableString,
                "production and conversion"
        )

Portrait: enter image description here

Landscape: enter image description here

Deva
  • 150
  • 2
  • 2
  • 17

1 Answers1

0

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)
    }
}
Cheticamp
  • 61,413
  • 10
  • 78
  • 131