1 package com.lixu.listviewrefresh;
2
3 import android.content.Context;
4 import android.util.AttributeSet;
5 import android.view.GestureDetector;
6 import android.view.MotionEvent;
7 import android.view.View;
8 import android.widget.AbsListView;
9 import android.widget.ListView;
10
11 public class MyRefreshListview extends ListView {
12 private OnRefreshListener mOnRefreshListener;
13 private Context context;
14 private int firstVisibleItem, visibleItemCount, totalItemCount;
15
16 public MyRefreshListview(Context context, AttributeSet attrs) {
17 super(context, attrs);
18 this.context = context;
19
20 }
21
22 public interface OnRefreshListener {
23
24 public void ontop();
25
26 public void onbuttom();
27 }
28
29 public void setOnRefreshListener(OnRefreshListener l) {
30 this.mOnRefreshListener = l;
31 // 这个方法可以解决当listview中初始没有数据的时候滑动来加载数据
32 final GestureDetector mGestureDetector = new GestureDetector(context,
33 new GestureDetector.SimpleOnGestureListener() {
34
35 // velocityY表示触摸停止点Y到触摸起始点Y的速度值 当两点距离值为负时,速度值也为负所以:
36 // >0表示从上往下拉
37 // <0表示从下往上拉
38 public boolean onFling(android.view.MotionEvent e1, android.view.MotionEvent e2, float velocityX,
39 float velocityY) {
40 if (velocityY > 0) {
41
42 // 滑动到顶部时添加
43 if (firstVisibleItem == 0) {
44
45 mOnRefreshListener.ontop();
46
47 }
48
49 }
50 if (velocityY < 0) {
51 // 滑动到底部时添加
52 if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
53
54 mOnRefreshListener.onbuttom();
55
56 }
57 }
58
59 return super.onFling(e1, e2, velocityX, velocityY);
60 };
61
62 });
63 this.setOnTouchListener(new OnTouchListener() {
64 // 将触摸事件交给GestureDetector来处理
65 @Override
66 public boolean onTouch(View v, MotionEvent event) {
67
68 return mGestureDetector.onTouchEvent(event);
69 }
70 });
71
72 this.setOnScrollListener(new OnScrollListener() {
73
74 @Override
75 public void onScrollStateChanged(AbsListView view, int scrollState) {
76
77 }
78
79 @Override
80 public void onScroll(AbsListView view, int fvi, int vic, int tic) {
81
82 firstVisibleItem = fvi;
83 visibleItemCount = vic;
84 totalItemCount = tic;
85
86 }
87 });
88
89 }
90
91 }
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 tools:context="com.lixu.listviewrefresh.MainActivity" >
6
7 <com.lixu.listviewrefresh.MyRefreshListview
8 android:id="@+id/listview"
9 android:layout_width="match_parent"
10 android:layout_height="match_parent" />
11
12 </RelativeLayout>
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="ma