LoginSignup
3
3

More than 3 years have passed since last update.

TextViewのEllipsizeする行数を動的に変更する

Posted at

TextViewの高さが親と兄弟のレイアウトによって可変になる場合に以下のように、長すぎるテキストが見切れてしまうことがあります。
figure1.png

linesellipsize を設定すれば良さそうですが、ビューの高さが可変なので 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
    }
}

結果はこのようになります。
4行表示できる高さでは4行で省略し、5行表示できる高さでは5行で省略します。
figure2.png

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3