在textview中获取当前可见文本

Joh*_*ohn 23 android textview

我在TextView中有一段很长的段落,它被ScrollView包裹着.有没有办法找到当前的可见文字?

我可以在textview中找到行数,行高,还可以从scrollview中找到scrollx和scrolly,但是找到当前显示文本的链接.请帮忙!谢谢.

小智 15

这样做很简单:

int start = textView.getLayout().getLineStart(0);
int end = textView.getLayout().getLineEnd(textView.getLineCount() - 1);

String displayed = textView.getText().toString().substring(start, end);
Run Code Online (Sandbox Code Playgroud)


小智 5

这里。获取显示的第一行的行号。然后获取第二个显示行的行号。然后获取文本并计算单词数。

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;
    }
Run Code Online (Sandbox Code Playgroud)


Sno*_*all 1

您声称您知道scrollY当前滚动的像素数。您还知道您正在考虑的窗口的高度(以像素为单位),因此将其称为scrollViewHeight。然后

int scrollY; // This is your current scroll position in pixels.
int scrollViewHeight; // This is the height of your scrolling window.
TextView textView; // This is the TextView we're considering.

String text = (String) textView.getText();
int charsPerLine = text.length() / textView.getLineCount();
int lineHeight = textView.getLineHeight();

int startLine = scrollY / lineHeight;
int endLine = startLine + scrollViewHeight/lineHeight + 1;

int startChar = charsPerLine * startLine;
int endChar = charsPerLine * (endLine+1) + 1;
String approxVisibleString = text.substring(startChar, endChar);
Run Code Online (Sandbox Code Playgroud)

这是一个近似值,因此请使用它作为最后的手段。