如何检查我的 ListView 是否具有可滚动的项目数? [英] How to check if a my ListView has scrollable number of items?
问题描述
您如何知道您的 ListView 是否有足够数量的项目以便它可以滚动?
How do you know if your ListView has enough number of items so that it can scroll?
例如,如果我的 ListView 上有 5 个项目,所有项目都将显示在一个屏幕上.但是如果我有 7 个或更多,我的 ListView 就会开始滚动.我如何知道我的列表是否可以以编程方式滚动?
For instance, If I have 5 items on my ListView all of it will be displayed on a single screen. But if I have 7 or more, my ListView begins to scroll. How do I know if my List can scroll programmatically?
推荐答案
Diegosan 的回答无法区分屏幕上部分可见的最后一项.这是该问题的解决方案.
Diegosan's answer cannot differentiate when the last item is partially visible on the screen. Here is a solution to that problem.
首先,ListView 必须在屏幕上呈现,然后我们才能检查其内容是否可滚动.这可以通过 ViewTreeObserver 来完成:
First, the ListView must be rendered on the screen before we can check if its content is scrollable. This can be done with a ViewTreeObserver:
ViewTreeObserver observer = listView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (willMyListScroll()) {
// Do something
}
}
});
这里是willMyListScroll()
:
boolean willMyListScroll() {
int pos = listView.getLastVisiblePosition();
if (listView.getChildAt(pos).getBottom() > listView.getHeight()) {
return true;
} else {
return false;
}
}
这篇关于如何检查我的 ListView 是否具有可滚动的项目数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!