3 回答
TA贡献2041条经验 获得超4个赞
最终,我找到了一个不太优雅的解决方案,但是对我有用。弄清楚onScroll方法是在滚动的每个步骤中调用的,而不仅仅是在滚动端被调用,并且onScrollStateChanged实际上仅在滚动完成时才被调用,我这样做是:
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted() {
if (this.currentVisibleItemCount > 0 && this.currentScrollState == SCROLL_STATE_IDLE) {
/*** In this way I detect if there's been a scroll which has completed ***/
/*** do the work! ***/
}
}
实际上,每次滚动ListView时,我都会保存有关第一个可见项和可见项计数的数据(onScroll方法);当滚动状态更改(onScrollStateChanged)时,我保存了状态,并调用了另一个方法,该方法实际上了解滚动是否完成以及滚动是否完成。这样,我也可以获得有关所需可见项目的数据。也许不干净,但是行得通!
TA贡献1804条经验 获得超3个赞
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (list.getLastVisiblePosition() == list.getAdapter().getCount() - 1
&& list.getChildAt(list.getChildCount() - 1).getBottom() <= list.getHeight()) {
// Scroll end reached
// Write your code here
}
}
TA贡献1943条经验 获得超7个赞
降低这种行为是棘手的,并且花了我相当长的时间才能使它变得完美。问题的根源在于,据我所知,滚动侦听器本身实际上还不足以检测“滚动停止”(包括方向按钮/轨迹球)。我最终做了一些符合我期望的工作。
我认为我能做到的最好方法是扩展ListView并重写一些方法:
....
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_UP) {
startWait();
}
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
stopWait();
}
if (event.getAction() == MotionEvent.ACTION_UP ||
event.getAction() == MotionEvent.ACTION_CANCEL) {
startWait();
}
return super.onTouchEvent(event);
}
private OnScrollListener customScrollListener = new OnScrollListener() {
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
stopWait();
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
startWait();
} else {
stopWait();
}
}
};
//All this waiting could be improved, but that's the idea
private Thread waitThread = null;
private int waitCount = Integer.MIN_VALUE;
public void stopWait() {
waitCount = Integer.MIN_VALUE;
}
public synchronized void startWait() {
waitCount = 0;
if (waitThread != null) {
return;
}
waitThread = new Thread(new Runnable() {
@Override
public void run() {
try {
for (; waitCount.get() < 10; waitCount++) {
Thread.sleep(50);
}
//Kick it back to the UI thread.
view.post(theRunnableWithYourOnScrollStopCode); // HERE IS WHERE YOU DO WHATEVER YOU WANTED TO DO ON STOP
} catch (InterruptedException e) {
} finally {
waitThread = null;
}
}
});
waitThread.start();
}
请注意,您还必须customScrollListener在构造函数中绑定。我认为该实现很好,因为它不会立即触发“事件”,因此会稍等一会,直到它完全停止滚动为止。
- 3 回答
- 0 关注
- 573 浏览
添加回答
举报