Android TextView:android:justificationMode =“inter_word”不适用于android:autoLink =“web”

Kis*_*nki 11 android hyperlink textview text-justify

我有一个文本视图,它必须android:justificationMode="inter_word"对齐 TextView 中的文本。

这工作正常。但现在,当我的 TextView 文本中有一个 URL 时,我想在单击该 URL 时打开浏览器。因此,为了实现这一目标,我添加了android:autoLink="web",但如果我这样做,那么文本对齐就会停止,可点击的链接开始工作。

<androidx.appcompat.widget.AppCompatTextView
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:justificationMode="inter_word"
   android:autoLink="web"
   android:text="" />
Run Code Online (Sandbox Code Playgroud)

笔记:

我也尝试过,

  1. 以编程方式进行活动 textview.setMovementMethod(LinkMovementMethod.getInstance());
  2. 在 XML 中 android:linksClickable="true"

但是,这些都无法实现这两个功能(带有理由文本的可点击链接)

如果有人已经实现了这两件事,请告诉我:TextView 中文本的对齐方式以及其中的可点击链接。

Moh*_*Zek 2

我长期以来一直在寻找一种解决方案,使理由和超链接一起工作,这对我有用。

<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
        }
Run Code Online (Sandbox Code Playgroud)

然后您可以按如下方式使用它。

   mainTV.showHtml(text)
Run Code Online (Sandbox Code Playgroud)