Вот хороший способ сделать это с расширением Kotlin. Обратите внимание, что нам нужно дождаться макета представления, прежде чем мы сможем измерить и добавить суффикс.
In 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)
}
})
}
In 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'
person
Markymark
schedule
23.08.2019
l.getEllipsisStart()
- person Pedro Oliveira   schedule 26.09.2014