我有一个全屏TextView,持有一个需要滚动的长跨度。 TextView的getLineCount()为我提供了整个文本块使用的总行数,但我想知道屏幕上当前可以看到多少行文本。
或者,更好的是,有没有办法找出屏幕上当前可见的线条范围?例如,当视图滚动时,我可以判断20-60行当前是否可见?
答案 0 :(得分:30)
我想出了答案:
int height = myTextView.getHeight();
int scrollY = myTextView.getScrollY();
Layout layout = myTextView.getLayout();
int firstVisibleLineNumber = layout.getLineForVertical(scrollY);
int lastVisibleLineNumber = layout.getLineForVertical(scrollY+height);
答案 1 :(得分:5)
为了使它们工作,您应该以这种方式编写@Robert发布的代码:
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);
}
});