TextViewの高さが親と兄弟のレイアウトによって可変になる場合に以下のように、長すぎるテキストが見切れてしまうことがあります。
lines
と ellipsize
を設定すれば良さそうですが、ビューの高さが可変なので lines
も可変にする必要があります。
この問題は以下のようにサブクラスを定義することで解決できます。
DynamicEllipsizeTextView
class DynamicEllipsizeTextView : TextView {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(
context,
attrs,
defStyleAttr,
defStyleRes
)
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
adjustEllipsize(bottom - top)
}
private fun adjustEllipsize(containerHeight: Int) {
// レイアウトが確保した高さ内に収まる行数に設定
val ableToShowLineCount = containerHeight / lineHeight
setLines(ableToShowLineCount)
// 更新を反映するために再度テキストを設定
text = text
}
}