Reputation: 15847
I want to get the number of lines of a text view
textView.setText("Test line 1 Test line 2 Test line 3 Test line 4 Test line 5.............")
textView.getLineCount();
always returns zero
Then I have also tried:
ViewTreeObserver vto = this.textView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewTreeObserver obs = textView.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
System.out.println(": " + textView.getLineCount());
}
});
It returns the exact output.
But this works only for a static layout.
When I am inflating the layout dynamically this doesn't work anymore.
How could I find the number of line in a TextView?
Upvotes: 73
Views: 91646
Reputation: 748
I have used the textView.lineCount method as well. I have a project where I want to show a maximum of 4 lines, then I identify whether or not I need to show a read more text if the actual text that goes into the text view needs more than 4 lines. It worked fine most of the time, but on some edge cases, the lineCount method returned 1 more then the actual visible lines (5 instead of 4). This resulted in Read More label getting presented but in reality, no more text to be read when it is clicked. (And I was waiting until the layout is rendered to check the line count)
After researching for some time, I found out that there is actually a method that works more reliably for my use case. I wanted to share if it helps anyone.
val maxTextLines = 4
textView.text = "Some string that may or may not exceed 4 lines"
val width = if (textView.lineCount >= (maxTextLines + 1)) {
textView.layout.getLineWidth(maxTextLines)
} else {
0f
}
if (width != 0f) {
readMoreView.visibility = VISIBLE
textView.maxLines = maxTextLines
readMoreView.setOnClickListener {
if (textView.maxLines == maxTextLines) {
textView.maxLines = Integer.MAX_VALUE
readMoreView.text = context.getString(R.string.read_less)
} else {
textView.maxLines = maxTextLines
readMoreView.text = context.getString(R.string.read_more)
}
}
} else {
readMoreView.visibility = GONE
}
I know the code above is not an exact response to this question but this logic of line width can be used in conjunction with the lineCount method to make sure it does not return an additional incorrect line which is essentially empty.
Upvotes: 0
Reputation: 1232
You could also use PrecomputedTextCompat
for getting the number of lines.
Regular method:
fun getTextLineCount(textView: TextView, text: String, lineCount: (Int) -> (Unit)) {
val params: PrecomputedTextCompat.Params = TextViewCompat.getTextMetricsParams(textView)
val ref: WeakReference<TextView>? = WeakReference(textView)
GlobalScope.launch(Dispatchers.Default) {
val text = PrecomputedTextCompat.create(text, params)
GlobalScope.launch(Dispatchers.Main) {
ref?.get()?.let { textView ->
TextViewCompat.setPrecomputedText(textView, text)
lineCount.invoke(textView.lineCount)
}
}
}
}
Call this method:
getTextLineCount(textView, "Test line 1 Test line 2 Test line 3 Test line 4 Test line 5.............") { lineCount ->
//count of lines is stored in lineCount variable
}
Or maybe you can create extension method for it like this:
fun TextView.getTextLineCount(text: String, lineCount: (Int) -> (Unit)) {
val params: PrecomputedTextCompat.Params = TextViewCompat.getTextMetricsParams(this)
val ref: WeakReference<TextView>? = WeakReference(this)
GlobalScope.launch(Dispatchers.Default) {
val text = PrecomputedTextCompat.create(text, params)
GlobalScope.launch(Dispatchers.Main) {
ref?.get()?.let { textView ->
TextViewCompat.setPrecomputedText(textView, text)
lineCount.invoke(textView.lineCount)
}
}
}
}
and then you call it like this:
textView.getTextLineCount("Test line 1 Test line 2 Test line 3 Test line 4 Test line 5.............") { lineCount ->
//count of lines is stored in lineCount variable
}
Upvotes: 10
Reputation: 980
textview.getText().toString().split(System.getProperty("line.separator")).length
It works fine for me to get number of lines of TextView.
Upvotes: 1
Reputation: 331
ViewTreeObserver
is not so reliable especially when using dynamic layouts such as ListView
.
Let's assume:
1. You will do some work depending on the lines of TextView
.
2. The work is not very urgent and can be done later.
Here is my solution:
public class LayoutedTextView extends TextView {
public LayoutedTextView(Context context) {
super(context);
}
public LayoutedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LayoutedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public interface OnLayoutListener {
void onLayouted(TextView view);
}
private OnLayoutListener mOnLayoutListener;
public void setOnLayoutListener(OnLayoutListener listener) {
mOnLayoutListener = listener;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (mOnLayoutListener != null) {
mOnLayoutListener.onLayouted(this);
}
}
}
Usage:
LayoutedTextView tv = new LayoutedTextView(context);
tv.setOnLayoutListener(new OnLayoutListener() {
@Override
public void onLayouted(TextView view) {
int lineCount = view.getLineCount();
// do your work
}
});
Upvotes: 33
Reputation: 4073
You can also calculate the amount of lines through this function:
private fun countLines(textView: TextView): Int {
return Math.ceil(textView.paint.measureText(textView.text.toString()) /
textView.measuredWidth.toDouble()).toInt()
}
Keep in mind that It may not work very well on a RecyclerView
though.
Upvotes: 3
Reputation: 912
textView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
// Remove listener because we don't want this called before _every_ frame
textView.getViewTreeObserver().removeOnPreDrawListener(this)
// Drawing happens after layout so we can assume getLineCount() returns the correct value
if(textView.getLineCount() > 2) {
// Do whatever you want in case text view has more than 2 lines
}
return true; // true because we don't want to skip this frame
}
});
Upvotes: 24
Reputation: 1981
I was able to get getLineCount()
to not return 0 using a post
, like this:
textview.setText(“Some text”);
textview.post(new Runnable() {
@Override
public void run() {
int lineCount = textview.getLineCount();
// Use lineCount here
}
});
Upvotes: 116
Reputation: 6368
Are you doing this onCreate
? The Views aren't laid out yet, so getLineCount()
is 0 for a while. If you do this later in the Window LifeCycle, you'll get your line count. You'll have a hard time doing it onCreate
, but onWindowFocusChanged
with hasFocus=true
usually has the Views measured by now.
The textView.post()
suggestion is also a good one
Upvotes: 0
Reputation: 17105
Based on @secnelis idea, there is even a more clean way if you target API 11 or higher.
Instead of extending a TextView
you can use already built-in functionality if View.OnLayoutChangeListener
In ListAdapter.getView()
, for instance
if (h.mTitle.getLineCount() == 0 && h.mTitle.getText().length() != 0) {
h.mTitle.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(final View v, final int left, final int top,
final int right, final int bottom, final int oldLeft,
final int oldTop, final int oldRight, final int oldBottom) {
h.mTitle.removeOnLayoutChangeListener(this);
final int count = h.mTitle.getLineCount();
// do stuff
}
});
} else {
final int count = h.mTitle.getLineCount();
// do stuff
}
Upvotes: 8
Reputation: 151
I think the crux of this question is that people want to be able to find out the size of a TextView in advance so that they can dynamically resize it to nicely fit the text. A typical use might be to create talk bubbles (at least that was what I was working on).
I tried several solutions, including use of getTextBounds() and measureText() as discussed here. Unfortunately, both methods are slightly inexact and have no way to account for line breaks and unused linespace. So, I gave up on that approach.
That leaves getLineCount(), whose problem is that you have to "render" the text before getLineCount() will give you the number of lines, which makes it a chicken-and-egg situation. I read various solutions involving listeners and layouts, but just couldn't believe that there wasn't something simpler.
After fiddling for two days, I finally found what I was looking for (at least it works for me). It all comes down to what it means to "render" the text. It doesn't mean that the text has to appear onscreen, only that it has to be prepared for display internally. This happens whenever a call is made directly to invalidate() or indirectly as when you do a setText() on your TextView, which calls invalidate() for you since the view has changed appearance.
Anyway, here's the key code (assume you already know the talk bubble's lineWidth and lineHeight of a single line based on the font):
TextView talkBubble;
// No peeking while we set the bubble up.
talkBubble.setVisibility( View.INVISIBLE );
// I use FrameLayouts so my talk bubbles can overlap
// lineHeight is just a filler at this point
talkBubble.setLayoutParams( new FrameLayout.LayoutParams( lineWidth, lineHeight ) );
// setText() calls invalidate(), which makes getLineCount() do the right thing.
talkBubble.setText( "This is the string we want to dynamically deal with." );
int lineCount = getLineCount();
// Now we set the real size of the talkBubble.
talkBubble.setLayoutParams( new FrameLayout.LayoutParams( lineWidth, lineCount * lineHeight ) );
talkBubble.setVisibility( View.VISIBLE );
Anyway, that's it. The next redraw will give a bubble tailor-made for your text.
Note: In the actual program, I use a separate bubble for determining lines of text so that I can resize my real bubble dynamically both in terms of length and width. This allows me to shrink my bubbles left-to-right for short statements, etc.
Enjoy!
Upvotes: 10