我有一个带有TextView的maxlines=3,我想使用自己的省略号,而不是
"Lore ipsum ..."
我需要
"Lore ipsum ... [See more]"
为了给用户一个提示,点击视图将展开全文。
有可能吗?
我正在考虑检查TextView是否有省略号,在这种情况下添加文本“查看更多”,并在前面设置省略号之后,但我找不到这样做的方法。
也许,如果我找到了文本被裁剪的位置,我可以禁用省略号,创建一个子字符串,然后添加“.查看更多”,但我还是不知道如何得到这个位置。
发布于 2019-08-23 21:25:28
这是一个用Kotlin分机做这件事的好方法。注意,在测量和追加后缀之前,我们需要等待视图进行布局。
在TextViewExtensions.kt
中
fun TextView.setEllipsizedSuffix(maxLines: Int, suffix: String) {
addOnLayoutChangeListener(object: View.OnLayoutChangeListener {
override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
val allText = text.toString()
var newText = allText
val tvWidth = width
val textSize = textSize
if(!TextUtil.textHasEllipsized(newText, tvWidth, textSize, maxLines)) return
while (TextUtil.textHasEllipsized(newText, tvWidth, textSize, maxLines)) {
newText = newText.substring(0, newText.length - 1).trim()
}
//now replace the last few chars with the suffix if we can
val endIndex = newText.length - suffix.length - 1 //minus 1 just to make sure we have enough room
if(endIndex > 0) {
newText = "${newText.substring(0, endIndex).trim()}$suffix"
}
text = newText
removeOnLayoutChangeListener(this)
}
})
}
在TextUtil.kt
中
fun textHasEllipsized(text: String, tvWidth: Int, textSize: Float, maxLines: Int): Boolean {
val paint = Paint()
paint.textSize = textSize
val size = paint.measureText(text).toInt()
return size > tvWidth * maxLines
}
然后实际使用它,像这样的myTextView.setEllipsizedSuffix(2, "...See more")
注意:如果您的文本来自服务器,并且可能有新的行字符,则可以使用此方法确定文本是否具有椭圆大小。
fun textHasEllipsized(text: String, tvWidth: Int, textSize: Float, maxLines: Int): Boolean {
val paint = Paint()
paint.textSize = textSize
val size = paint.measureText(text).toInt()
val newLineChars = StringUtils.countMatches(text, "\n")
return size > tvWidth * maxLines || newLineChars >= maxLines
}
StringUtils
来自implementation 'org.apache.commons:commons-lang3:3.4'
https://stackoverflow.com/questions/26054717
复制相似问题