ListView的滑动监听
大部分重写ListView都是在滑动事件上下功夫,以达到特殊的效果。
有时候还会使用GestureDetector手势识别、VelocityTracker滑动速度检测等辅助类。
listView的滑动监听主要有两个类:onTouchListener
、onScrollListener
onTouchListener:
listView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("logi", "down");
break;
case MotionEvent.ACTION_MOVE:
Log.i("logi", "move");
break;
case MotionEvent.ACTION_UP:
Log.i("logi", "up");
break;
}
return false;
}
});
onScrollListener():
listView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("logi", "down");
break;
case MotionEvent.ACTION_MOVE:
Log.i("logi", "move");
break;
case MotionEvent.ACTION_UP:
Log.i("logi", "up");
break;
}
return false;
}
});
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override // 状态改变时调用
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
switch (scrollState) {
case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
Log.i("logi", "进入惯性滑动状态");
break;
case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
Log.i("logi", "进入正在滑动状态");
break;
case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
Log.i("logi", "滑动停止状态");
break;
}
}
@Override // 滑动时调用
public void onScroll(AbsListView absListView, int firstVisibleItem, int
visibleItemCount, int totalItemCount) {
Log.i("logi", "滑动中");
Log.i("logi", "当前可以看到的第一个item的id为" + firstVisibleItem);
Log.i("logi", "当前总共可以看到" + visibleItemCount + "个Item");
Log.i("logi", "整个listView有" + visibleItemCount + "个Item");
if (firstVisibleItem + visibleItemCount == totalItemCount &&
totalItemCount > 0) {
Log.i("Logi", "滚动到了底部");
}
if (firstVisibleItem > lastItem) {
Log.i("logi", "向下滑动");
}
if (firstVisibleItem < lastItem) {
Log.i("logi", "向上滑动");
}
}
});
}
我们也可以通过listView获取区域内第一个和最后一个item的id
listView.getFirstVisiblePosition();
listView.getLastVisiblePosition();