Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way of retrieving a TextView's visible line count or range?

Tags:

I have a full-screen TextView holding a long Spanned that requires scrolling. The TextView's getLineCount() gives me the total number of lines used for the entire block of text but I'd like to know how many lines of text are currently visible on the screen.

Or, better yet, is there a way to figure out the range of lines currently visible on the screen? For example, as the view scrolls, can I tell that lines 20-60 are currently visible?

like image 904
Robert Nekic Avatar asked Feb 10 '10 18:02

Robert Nekic


2 Answers

I figured out the answer:

int height    = myTextView.getHeight(); int scrollY   = myTextView.getScrollY(); Layout layout = myTextView.getLayout();  int firstVisibleLineNumber = layout.getLineForVertical(scrollY); int lastVisibleLineNumber  = layout.getLineForVertical(scrollY+height); 
like image 103
Robert Nekic Avatar answered Nov 08 '22 05:11

Robert Nekic


To make them work you should write the code posted by @Robert in this way:

ViewTreeObserver vto = txtViewEx.getViewTreeObserver();         vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {             @Override             public void onGlobalLayout() {                 ViewTreeObserver obs = txtViewEx.getViewTreeObserver();                 obs.removeOnGlobalLayoutListener(this);                 height = txtViewEx.getHeight();                 scrollY = txtViewEx.getScrollY();                 Layout layout = txtViewEx.getLayout();                  firstVisibleLineNumber = layout.getLineForVertical(scrollY);                 lastVisibleLineNumber = layout.getLineForVertical(height+scrollY);              }         }); 
like image 41
Souhaieb Avatar answered Nov 08 '22 05:11

Souhaieb