Reputation: 71
In my app, I need text in myTextView to display single line without the three dots at the end. I need to show a little differently formatted text when it's too long, so something like setting maxHeight won't help since it just crops it.
My approach was to check how many lines the TextView has, and make the text in shorter if it has more than 1. This is exactly the approach I want, but since the View has to be drawn first to check LineCount, two-line layout flashes briefly before cutting the text to one-line:
myTextView.Post(() =>
{
if (myTextView.LineCount > 1)
{
// make text shorter here to fit 1 line
}
});
So my question is, is there any way to check how many lines the View will have before it is displayed to the user? I could force it based on character count in a string, but that seems wrong.
Upvotes: 0
Views: 932
Reputation: 71
So I came to a solution that works for me. It requires getting the screen width, calculating the width of the TextView and checking text length, everything in dp. So:
// get the screen width
var metrics = Resources.DisplayMetrics;
var widthInDp = (int)((metrics.WidthPixels) / metrics.Density);
// this line is very specific, it calculates the real usable space
// in my case, there was padding of 5dp nine times, so subtract it
var space = widthInDp - 9 * 5;
// and in this usable space, I had 7 identical TextViews, so a limit for one is:
var limit = space / days.Length;
// now calculating the text length in dp
Paint paint = new Paint();
paint.TextSize = myTextView.TextSize;
var textLength = (int)Math.Ceiling(paint.MeasureText(myTextView.Text, 0, myTextView.Text.Length) / metrics.Density);
// and finally formating based of if the text fits (again, specific)
if (textLength > limit)
{
myTextView.Text = myTextView.Text.Substring(0, myTextView.Text.IndexOf("-"));
}
It's pretty simple approach now that I look at it, but I'll just leave it here and maybe someone will find it useful.
Upvotes: 0
Reputation: 540
Firstly, set TextView Visibility to Invisible so that it takes up its space and then populate it.
There is a method that you can use to get the line count.
TextView txt = (TextView)findViewById(R.id.txt);
txt.getLineCount();
This returns an "int". Use that int in your textChangedListener to play with the visibility of TextView.
This way you will know that how many line break does the TextView has.
Cheers.
Upvotes: 1