Ответ 1
Это легко сделать:
int start = textView.getLayout().getLineStart(0);
int end = textView.getLayout().getLineEnd(textView.getLineCount() - 1);
String displayed = textView.getText().toString().substring(start, end);
У меня есть длинный проход в TextView, который обернут ScrollView. Есть ли способ найти текущий видимый текст?
Я могу найти количество строк, высоту строки в textview, а также scrollx и прокручивать из scrollview, но найти ссылку на текущий отображаемый текст. Пожалуйста помоги! Спасибо.
Это легко сделать:
int start = textView.getLayout().getLineStart(0);
int end = textView.getLayout().getLineEnd(textView.getLineCount() - 1);
String displayed = textView.getText().toString().substring(start, end);
Вы утверждаете, что знаете 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);
Это приближение, поэтому используйте его как последнее средство.
Здесь. Получить номер строки первой отображаемой строки. Затем введите номер строки второй отображаемой строки. Затем получите текст и подсчитайте количество слов.
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;
}
У меня тоже есть о той же самой проблеме. Мне понадобилась первая видимая строка из текстового просмотра, видимого в настоящее время в recyclerview. Если вы пытаетесь получить в настоящее время первую строку текста в recyclerview, вы можете использовать следующий код:
TextView tv = (TextView) recyclerView.getChildAt(0); //gets current visible child view
// this is for top visible
//view or the textview directly
Rect r1 = new Rect();
tv.getHitRect(r1);//gets visible rect of textview
Layout l = tv.getLayout();
int line = l.getLineForVertical(-1 * r1.top);//first visible line
int start = l.getLineStart(line);//visible line start
int end = l.getLineEnd(line);//visible line end
String displayed = tv.getText().toString().substring(start, end);
попробуйте использовать getEllipsisStart()
int end = textView.getLayout().getEllipsisStart(0);
Использование textView.getLayout(). getEllipsisStart (0) работает только в том случае, если android: singleLine = "true"
Вот решение, которое будет работать, если Android: maxLines установлен:
public static String getVisibleText(TextView textView) {
// test that we have a textview and it has text
if (textView==null || TextUtils.isEmpty(textView.getText())) return null;
Layout l = textView.getLayout();
if (l!=null) {
// find the last visible position
int end = l.getLineEnd(textView.getMaxLines()-1);
// get only the text after that position
return textView.getText().toString().substring(0,end);
}
return null;
}
Помните: это работает после того, как представление уже загружено.
Применение:
textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
Log.i("test" ,"VisibleText="+getVisibleText(textView));
}
});