如何在Android的TextView中的特定单词之前插入换行符,如果行数超过一个



例如,我要在 TextView 中设置一个字符串"一二三四五"。

如果文本仅占一行,则没有变化,没关系

如果文本占据两行,则:

  • 预期结果为:"一二三四五"(正好在之后"二"(
  • 实际结果为:"一二三四五"(换行符可以在任何地方(

此外,我在约束布局中有一个宽度为零的空白文本视图,因此在设置文本之前我不知道文本视图的宽度。

我怎样才能做到这一点?

据我所知,文本的宽度可以在设置文本之前测量并除以文本视图的宽度,但不幸的是它对我不起作用,因为我不知道文本视图的宽度。

这是我的代码:

override fun setText(textView: TextView, prefix: String, postfix: String) {
    var fullText = "$prefix $postfix"
    val lines = getLinesCount(textView, fullText)
    if (lines > 1) {
        fullText = fullText.replace(postfix, "n$postfix")
    }
    textView.text = fullText
}
private fun getLinesCount(textView: TextView, text: String): Int {
    val paint = Paint()
    paint.textSize = textView.textSize
    val rect = Rect()
    paint.getTextBounds(text, 0, text.length, rect)
    // I'm not sure how to calculate textView actual width
    return (ceil(rect.width().toFloat() / textView.width)).toInt() 
}

TextView 支持在 UI 上绘制文本视图后返回行数getLineCount();

int lineCount = textView.getLineCount();
if(lineCount > 2) {
    //your line break logic goes here.
} else {
    //normal logic
}

请参阅此文档。

您需要使用 Html.fromHtml() 将 XML 文本视图的格式设置为 html 格式。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    textView.setText(Html.fromHtml("One two <br> three four five", Html.FROM_HTML_MODE_COMPACT));
} else { 
    textView.setText(Html.fromHtml("One two <br> three four five"));
}

您也可以参考此链接

相关内容

最新更新