Setting Ellipsize on TextView reduces lines shown by one (instead of only ellipsizing last)

可紊 提交于 2019-11-28 15:58:55
Vishwa Patel

This is by far the simplest solution I've found and am currently using in deployment. Let me know if you need any other assistance!

Oh and remember to remove the android:ellipsize tag in your XML since you will be using the bottom code to automatically ellipsize at the end of 3 lines.

TextView snippet;
snippet.setText("loren ipsum dolor loren ipsum dolor loren ipsum dolor loren ipsum dolor loren ipsum dolor loren ipsum dolor loren ipsum dolor loren ipsum dolor loren ipsum dolor loren ipsum dolor loren ipsum dolor loren ipsum dolor loren ipsum dolor loren ipsum dolor ")
ViewTreeObserver vto = this.snippet.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        ViewTreeObserver obs = snippet.getViewTreeObserver();
        obs.removeGlobalOnLayoutListener(this);
        if (snippet.getLineCount() > 3) {
            int lineEndIndex = snippet.getLayout().getLineEnd(2);
            String text = snippet.getText().subSequence(0, lineEndIndex - 3) + "...";
            snippet.setText(text);
        }
    }
});
irscomp

Just set android:maxLines and android:ellipsize.

<TextView
        android:id="@+id/tv_dua"
        android:ellipsize="end"
        android:maxLines="3"
        android:text="long text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

Use the following to get a multiline textview with ellipsis on the last line :

android:maxLines="4"
android:ellipsize="end"
android:singleLine="false"

Replace 4 with the number of lines you want. Hope it helps !

I tried it out with maxLines and ellipsize on Android 7 & 8.

android:maxLines="3"
android:ellipsize="end"

The preview shows 2 lines and on the third line "...".

But this seems to be a bug in the previewer.

On the device it just works fine, 3 lines with text, at the end of the third line "..."

Just use ellipsize combined with scrollHorizontally="true". Simple & clean.

It worked perfectly for me.

Vinothkumar Arputharaj

Try it

tv.setSingleLine(false);
tv.setEllipsize(TextUtils.TruncateAt.END);
int n = 3; // the exact number of lines you want to display
tv.setLines(n);

refer Programmatically create TextView with ellipsis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!