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.
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);
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With