I have a TextView whose height would vary based on the other components in the screen. I have a long text to be set in this TextView and hence I would like to ellipsize it. Simply specifying android:ellipsize="end" is not working. Only on specifying maxLines along with it, the ellipsizing works. But I cannot specify a value for maxLines since the height of TextView is dynamic. How do I get the text ellipsized without specifying maxLines for the TextView?
Asked
Active
Viewed 3,616 times
9
-
android:ellipsize="end" ,if I got you right – Levon Petrosyan Oct 09 '17 at 08:49
-
1Simply specifying android:ellipsize="end" is not working. Only on specifying maxLines along with it, the ellipsizing works. – DevAndroid Oct 09 '17 at 08:50
-
better append ... at the end or your string value – Ankit Aman Oct 09 '17 at 08:52
-
Share your xml code – Sushant Gosavi Oct 09 '17 at 08:54
-
@AnkitAman I can't do that since I wouldn't know where exactly I need to append ... – DevAndroid Oct 09 '17 at 08:57
-
@sushantgosavi Here it is https://www.dropbox.com/s/v4b19h8vonnjonu/ellipsize_not_working.xml?dl=0 – DevAndroid Oct 09 '17 at 09:15
-
Why the downvote? Is it not a valid question? – DevAndroid Oct 09 '17 at 10:12
1 Answers
18
I found the solution to the problem by adding global layout listener. Following is the code snippet
tvDesc.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
tvDesc.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int noOfLinesVisible = tvDesc.getHeight() / tvDesc.getLineHeight();
tvDesc.setText(R.string.desc);
tvDesc.setMaxLines(noOfLinesVisible);
tvDesc.setEllipsize(TextUtils.TruncateAt.END);
}
});

Community
- 1
- 1

DevAndroid
- 1,150
- 1
- 10
- 23
-
1Solution works, I just wanted to add that you have to remove `android:ellipsize="end"` in the layout xml to make it work. – Benjamin Bisinger Jul 18 '18 at 11:51