I have a textview that has android:justificationMode="inter_word" to justify text in the TextView.
This is working fine. But now, when I have a URL in my TextView's text, then I want to open the browser on clicking that URL. So to achieve this, I have added android:autoLink="web", but if I am doing this, then text justification stops and link clickable starts working.
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:justificationMode="inter_word"
android:autoLink="web"
android:text="" />
note:
I have also tried,
textview.setMovementMethod(LinkMovementMethod.getInstance());android:linksClickable="true"But, none of these is able to achieve both the feature (clickable links with justification text)
Do let me know if someone has achieved both things, Justification of text in TextView with clickable links in it.
I have been looking for a solution for a long time to make justification and hyperlink work together, and this works for me.
<TextView
android:id="@+id/mainTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="20dp"
android:layout_marginVertical="48dp"
android:clipToPadding="false"
android:justificationMode="inter_word"
android:fontFamily="@font/bbc_nassim_bold"
android:textColor="@color/color_2e2e2e"
android:textSize="20sp"/>
fun TextView.showHtml(html: String) {
this.text = HtmlCompat.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
this.setOnTouchListener { tv, event ->
require(tv is TextView)
val action = event.action
if (action == MotionEvent.ACTION_UP) {
val x = event.x.toInt() - tv.totalPaddingLeft + tv.scrollX
val y = event.y.toInt() - tv.totalPaddingTop + tv.scrollY
val line = tv.layout.getLineForVertical(y)
val offset = tv.layout.getOffsetForHorizontal(line, x.toFloat())
val spannable = SpannableString(text)
val links: Array<ClickableSpan> =
spannable.getSpans(offset, offset, ClickableSpan::class.java)
if (links.isNotEmpty()) {
links.first().onClick(tv)
}
}
true
}
You can then use it as below.
mainTV.showHtml(text)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With