Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of lines of TextView?

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?

like image 548
MAC Avatar asked Aug 20 '12 12:08

MAC


People also ask

How do I limit the number of lines in a TextView?

gpetuhov/textview_limit_text. txt. This will limit number of lines to 1 and if text exceeds limit, TextView will display ... in the end of line.

What attribute changes the size of TextView?

To use preset sizes to set up the autosizing of TextView in XML, use the android namespace and set the following attributes: Set the autoSizeText attribute to either none or uniform. none is a default value and uniform lets TextView scale uniformly on horizontal and vertical axes.

What is TextView?

A TextView displays text to the user and optionally allows them to edit it. A TextView is a complete text editor, however the basic class is configured to not allow editing.


2 Answers

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     } }); 
like image 116
Marilia Avatar answered Sep 20 '22 23:09

Marilia


As mentioned in this post,

getLineCount() will give you the correct number of lines only after a layout pass.

It means that you need to render the TextView first before invoking the getLineCount() method.

like image 22
aymeric Avatar answered Sep 19 '22 23:09

aymeric