Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textview.getLineCount always 0 in android

I'm trying to dynamically resize my textview but getlinecount() method always returns me 0 even after settext() and invalidate(). I'm using the following code:

if (convertView == null) {     convertView = lInflater.inflate(R.layout.listview, null);     holder = new ViewHolder();     holder.text2 = (TextView)convertView.findViewById(R.id.TextView02);     convertView.setTag(holder); } else {     holder = (ViewHolder)convertView.getTag(); }  holder.text2.setText(arr2[position]); holder.text2.invalidate();  int lineCnt = holder.text2.getLineCount(); 

holder is a static class as follows:

static class ViewHolder {     TextView text2; } 

holder contains non null text2 and the content set is also non null.

like image 491
neha Avatar asked Aug 20 '10 07:08

neha


2 Answers

In order to fix this issue apply the following lines:

textView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {     @Override     public void onGlobalLayout() {         if (textView.getLineCount() > 1) {             textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);         }     } }); 

The OnGlobalLayoutListener will be called after every change to the TextView (after measuring it, drawing it, ..). Here you can catch changes to your TextView before it'll be drawn to the screen and do whatever you need with it.

The last line in the code is to remove the listener, it's important since we don't want to continue catching each layout change.

like image 34
Nativ Avatar answered Oct 18 '22 02:10

Nativ


I know this question is quite old, but in case anyone comes here looking for the actual answer:

holder.text2.setText(arr2[position]); holder.text2.post(new Runnable() {     @Override     public void run() {         int lineCnt = holder.text2.getLineCount();         // Perform any actions you want based on the line count here.     } }); 
like image 131
Scott Avatar answered Oct 18 '22 02:10

Scott