gpt4 book ai didi

android - 带有 LinkMovementMethod 的 justificationMode 使文本被截断

转载 作者:行者123 更新时间:2023-12-05 03:39:11 25 4
gpt4 key购买 nike

我想同时实现文本对齐和向 TextView 添加链接(显示更多),所以我将 justificationModemovementMethod 一起使用。justificationMode 运行良好,但在设置 movementMethod 后,我的 TextView 每一行的最后一个字符被剪切。

val textView = findViewById<TextView>(R.id.myTextView)
textView.text = "Lorem ipsum dolor sit amet, consectetuabc adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
textView.justificationMode = JUSTIFICATION_MODE_INTER_WORD
textView.movementMethod = LinkMovementMethod()

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/myTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="16dp"
android:layout_marginTop="10dp"
android:textSize="20sp" />

</LinearLayout>

最佳答案

8 个月后,这个问题仍然存在,我只是在 SDK 31 上遇到了它。android:autoLink="all" 解决方法对我不起作用,对我的应用程序也不满意.这是我的解决方法;它并不完美,但它为我解决了这个问题,我认为这里足以解决 OP 的问题,同时为其他人提供指导:

<强>1。给TextView添加OnTouchListener

// A lot of this code was lifted from LinkMovementMethod.onTouchEvent
binding.tv.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 = tv.text as SpannedString // Risky business
val links: Array<ClickableSpan> = spannable.getSpans(offset, offset, ClickableSpan::class.java)
if (links.isNotEmpty()) {
logger.debug("x=${event.x}; y=${event.y}")
links.first().onClick(tv)
}
}
true
}

<强>2。将 ClickableSpans 添加到 TextView

val builder = SpannableStringBuilder()
builder.setSpan(object : ClickableSpan() {
// You can cache data here using closure
val textOrUrl = "Clicked!"
override fun onClick(widget: View) {
// Do stuff
Toast.makeText(widget.context, textOrUrl, Toast.LENGTH_SHORT).show()
}

// optional override if you don't want your links formatted
override fun updateDrawState(ds: TextPaint) = Unit
}, beginIndex, endIndex, 0)
// Add builder to TextView
binding.tv.text = builder

关于android - 带有 LinkMovementMethod 的 justificationMode 使文本被截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68660290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com