首页 > 代码库 > Android--判断listview上下滑动的方法

Android--判断listview上下滑动的方法

 1         elv_music_res_fragment.setOnScrollListener(new AbsListView.OnScrollListener() {
 2             private int mLastFirstPostion = 0;
 3             private int mLastFirstTop = 0;
 4             private int touchSlop = ViewConfiguration.get(getActivity()).getScaledTouchSlop();
 5 
 6             @Override
 7             public void onScrollStateChanged(AbsListView view, int scrollState) {
 8 
 9             }
10 
11             @Override
12             public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
13                 int currentTop;
14 
15                 View firstChildView = absListView.getChildAt(0);
16                 if (firstChildView != null) {
17                     currentTop = absListView.getChildAt(0).getTop();
18                 } else {
19                     //ListView初始化的时候会回调onScroll方法,此时getChildAt(0)仍是为空的
20                     return;
21                 }
22                 //判断上次可见的第一个位置和这次可见的第一个位置
23                 if (firstVisibleItem != mLastFirstPostion) {
24                     //不是同一个位置
25                     if (firstVisibleItem > mLastFirstPostion) {
26                         //
27                         if (rg_container_resFragment.getVisibility() != View.GONE) {
28                             rg_container_resFragment.setVisibility(View.GONE);
29                         }
30                     } else {
31                         //
32                         if (rg_container_resFragment.getVisibility() != View.VISIBLE) {
33                             rg_container_resFragment.setVisibility(View.VISIBLE);
34                         }
35                     }
36                     mLastFirstTop = currentTop;
37                 } else {
38                     //是同一个位置
39                     if (Math.abs(currentTop - mLastFirstTop) > touchSlop) {
40                         //避免动作执行太频繁或误触,加入touchSlop判断,具体值可进行调整
41                         if (currentTop > mLastFirstTop) {
42                             //
43                             if (rg_container_resFragment.getVisibility() != View.VISIBLE) {
44                                 rg_container_resFragment.setVisibility(View.VISIBLE);
45                             }
46                         } else if (currentTop < mLastFirstTop) {
47                             //
48                             if (rg_container_resFragment.getVisibility() != View.GONE) {
49                                 rg_container_resFragment.setVisibility(View.GONE);
50                             }
51                         }
52                         mLastFirstTop = currentTop;
53                     }
54                 }
55                 mLastFirstPostion = firstVisibleItem;
56             }
57         });

 

Android--判断listview上下滑动的方法