Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current visible text in textview

Tags:

I have a long passage in a TextView which is wrapped around by ScrollView. Is there any way to find the current visible text?

I can find the number of lines, line height in textview and also scrollx and scrolly from scrollview, but find the linkage to the current displayed text. Please help! Thanks.

like image 379
John Avatar asked Dec 26 '11 15:12

John


2 Answers

It is simple to do this:

int start = textView.getLayout().getLineStart(0); int end = textView.getLayout().getLineEnd(textView.getLineCount() - 1);  String displayed = textView.getText().toString().substring(start, end); 
like image 162
Kim Avatar answered Oct 13 '22 16:10

Kim


Here. Get the line number of the first displayed line. Then get the line number of the second displayed line. Then get the text and count the number of words.

private int getNumberOfWordsDisplayed() {         int start = textView.getLayout().getLineStart(getFirstLineIndex());         int end = textView.getLayout().getLineEnd(getLastLineIndex());         return textView.getText().toString().substring(start, end).split(" ").length;     }      /**      * Gets the first line that is visible on the screen.      *      * @return      */     public int getFirstLineIndex() {         int scrollY = scrollView.getScrollY();         Layout layout = textView.getLayout();         if (layout != null) {             return layout.getLineForVertical(scrollY);         }         Log.d(TAG, "Layout is null: ");         return -1;     }      /**      * Gets the last visible line number on the screen.      * @return last line that is visible on the screen.      */     public int getLastLineIndex() {         int height = scrollView.getHeight();         int scrollY = scrollView.getScrollY();         Layout layout = textView.getLayout();         if (layout != null) {             return layout.getLineForVertical(scrollY + height);         }         return -1;     } 
like image 29
LifeQuestioner Avatar answered Oct 13 '22 16:10

LifeQuestioner