在我的 Android 应用程序中,我创建了 8 个堆叠在一起的 TextView。现在我想将一些纯文本加载到那些 TextView-Lines 中。目前我的字符串有一个“;”作为指示换行符的分隔符,但是如果我自动检测换行符而不是使用硬编码的分号方法会方便得多。
目前这是我的字符串:
myString = "" +
"This seems to be some sort of spaceship,;" +
"the designs on the walls appear to be of;" +
"earth origin. It looks very clean here.;"
在我的其他类(class)中,我将此字符串加载到 8 个 TextView 中,我已使用“;”将其加载到 ArrayList 中。作为分隔符。
public fun fillLines(myString: String) {
// How To Make Line Breaks Automatic??
for(i: Int in str until myString.split(";").size) {
if(i > textViewArray.size - 1) {
break
}
textViewArray[i].text = myString.split(";")[i]
textViewArray[i].alpha = 1.0f
}
}
有什么方法可以获得与上面所示相同的结果,但无需将分隔符硬编码为“;”而是以某种方式自动检测 TextView 内部发生的换行符,然后将其用作分隔符以推进所有 8 个 TextView“行”。
我需要 8 个 TextView 作为单独的“文本行”堆叠在一起的原因是因为我想使用一种动画技术。
最佳答案
换行变得相当复杂,所以我的建议是您允许 TextView
执行测量和布局以确定换行。您可以拥有一个与其他 View 具有相同样式的不可见 TextView
,并将其附加到布局,使其具有与您的各个 TextView
实例相同的宽度。从那里添加一个布局更改监听器,然后您可以从 TextView
Layout
中检索各个行:
myTextView.text = // your text string here
myTextView.addOnLayoutChangeListener { view, _, _, _, _, _, _, _, _ ->
(view as? TextView)?.layout?.let { layout ->
// Here you'll have the individual broken lines:
val lines = (0 until layout.lineCount).map {
layout.text.subSequence(layout.getLineStart(it), layout.getLineVisibleEnd(it)
}
}
}
也就是说,这伴随着一个警告,即您将失去 TextView
提供的连字符,因此您可能希望在您的情况下完全禁用连字符。
关于android - 如何检测 TextView 中的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53888490/