ListView 下拉刷新

最近因为公司的项目,做了一个关于ListView下拉刷新的demo,供大家学习参考,有好的建议也希望提供给我。下面为demo的详细:

 

呈现主界面的Activity:

public class MyActivity extends Activity implements PullToRefreshListView.OnRefreshListener{

    private static final String TAG = "PullToRefreshListView";

    private PullToRefreshListView pullToRefreshListView;
    private ArrayList<HashMap<String,String>> list;
    private HashMap<String,String> map;
    private MainAdapter mainAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v(TAG, "onCreate");
        setData();
        pullToRefreshListView = (PullToRefreshListView)findViewById(R.id.bodyList);

        mainAdapter = new MainAdapter(MyActivity.this,list);

        pullToRefreshListView.setOnRefreshListener(this);  //设置刷新监听
        pullToRefreshListView.setAdapter(mainAdapter);
    }

    private void setData(){
        list = new ArrayList<HashMap<String, String>>();
        map = new HashMap<String, String>();
        map.put("test1","test1");
        list.add(map);
    }

  @Override
    public Object refreshing() {
        setData();
        return null;
    }
}

 封装数据的Adapter:

public class MainAdapter extends BaseAdapter {

    private ArrayList<HashMap<String,String>> list;
    private Context context;
    private LayoutInflater myInflater;

    public  MainAdapter(Context context,ArrayList<HashMap<String,String>> list){
        this.context = context;
        this.list = list;
        this.myInflater = LayoutInflater.from(this.context);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return this.list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        HolderView holderView = null;
        if (view == null){
            holderView = new HolderView();
            view = this.myInflater.inflate(R.layout.main_item,null);
            holderView.textView = (TextView)view.findViewById(R.id.main_item);
            view.setTag(holderView);
        } else {
            holderView = (HolderView)view.getTag();
        }
        holderView.textView.setText(list.get(i).get("test1"));
        return view;
    }

    class HolderView{
         TextView textView;
    }
}

 自定义下拉刷新的ListView:

public class PullToRefreshListView extends ListView implements OnScrollListener {

    private static final String TAG = "PullToRefreshListView";

    private final static int RELEASE_To_REFRESH = 0;// 松手刷新状态
    private final static int PULL_To_REFRESH = 1;// 下拉刷新状态
    private final static int REFRESHING = 2;// 刷新中的状态
    private final static int DONE = 3;// 正常状态
    private int mPullRefreshState;// 记录下拉刷新状态

    // 实际的padding的距离与界面上偏移距离的比例
    private final static int RATIO = 2;

    // HeadView控件
    private LayoutInflater inflater;
    private LinearLayout mHeaderLayout;
    private TextView tipTextView;
    private TextView lastUpdatedTextView;
    private ImageView arrowImageView;
    private ProgressBar progressBar;

    // HeadView箭头动画
    private RotateAnimation animation;
    private RotateAnimation reverseAnimation;

    private boolean isRecored;// 用于保证startY的值在一个完整的touch事件中只被记录一次
    private boolean isBack;
    private int mHeaderHight;
    private int startY;
    private int firstVisiableItem;// 位于ListView第一行的Item的Index

    // 定义接口
    public interface OnRefreshListener {
        Object refreshing(); // 加载数据
    }

    // 注入接口
    private OnRefreshListener mRefreshListener = null;

    public void setOnRefreshListener(OnRefreshListener mRefreshListener) {
        this.mRefreshListener = mRefreshListener;
    }

    public PullToRefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    // 初始化ListView
    private void init(Context context) {
        inflater = LayoutInflater.from(context);
        mHeaderLayout = (LinearLayout) inflater.inflate(
                R.layout.pull_to_refresh_header, null);
        arrowImageView = (ImageView) mHeaderLayout
                .findViewById(R.id.head_imageView);
        arrowImageView.setMinimumWidth(70);
        arrowImageView.setMinimumHeight(50);
        progressBar = (ProgressBar) mHeaderLayout
                .findViewById(R.id.head_progressBar);
        tipTextView = (TextView) mHeaderLayout
                .findViewById(R.id.head_tipTextView);
        lastUpdatedTextView = (TextView) mHeaderLayout
                .findViewById(R.id.head_lastUpdateTextView);

        measureView(mHeaderLayout);
        mHeaderHight = mHeaderLayout.getMeasuredHeight();

        // 初始隐藏HeadView
        mHeaderLayout.setPadding(0, -1 * mHeaderHight, 0, 0);
        mHeaderLayout.invalidate();

        addHeaderView(mHeaderLayout, null, false);
        setOnScrollListener(this);

        animation = new RotateAnimation(0, -180,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        animation.setInterpolator(new LinearInterpolator());
        animation.setDuration(250);
        animation.setFillAfter(true);
        reverseAnimation = new RotateAnimation(-180, 0,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        reverseAnimation.setInterpolator(new LinearInterpolator());
        reverseAnimation.setDuration(200);
        reverseAnimation.setFillAfter(true);

        mPullRefreshState = DONE;
    }

    /**
     * 因为是在构造函数里测量高度,应该先measure一下
     *
     * @param child
     */
    private void measureView(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
                    MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeMeasureSpec(0,
                    MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }

    @Override
    public void onScroll(AbsListView view, int firstVisiableItem,
                         int visibleItemCount, int totalItemCount) {
        this.firstVisiableItem = firstVisiableItem;
    }

    /**
     * ListView的scrollState有3种值:SCROLL_STATE_IDLE, SCROLL_STATE_TOUCH_SCROLL,
     * SCROLL_STATE_FLING, 而我们要下拉的触发条件是SCROLL_STATE_TOUCH_SCROLL。
     */
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (firstVisiableItem == 0 && !isRecored) {
                    isRecored = true;
                    startY = (int) event.getY();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                int tempY = (int) event.getY();
                if (!isRecored && firstVisiableItem == 0) {
                    isRecored = true;
                    startY = tempY;
                }
                if (mPullRefreshState != REFRESHING && isRecored) {
                    // 保证在设置padding的过程中,当前的位置一直是在head,否则如果当列表超出屏幕的话,当在上推的时候,列表会同时进行滚动
                    // 可以松手去刷新了
                    if (mPullRefreshState == RELEASE_To_REFRESH) {
                        setSelection(0);
                        // 往上推了,推到了屏幕足够掩盖head的程度,但是还没有推到全部掩盖的地步
                        if (((tempY - startY) / RATIO < mHeaderHight)
                                && (tempY - startY) > 0) {
                            mPullRefreshState = PULL_To_REFRESH;
                            changeHeaderViewByState();
                            Log.v(TAG, "由松开刷新状态转变到下拉刷新状态");
                        } else if (tempY - startY <= 0) {// 一下子推到顶了
                            mPullRefreshState = DONE;
                            changeHeaderViewByState();
                            Log.v(TAG, "由松开刷新状态转变到Done状态");
                        } else {// 往下拉了,或者还没有上推到屏幕顶部掩盖head的地步
                            // 不用进行特别的操作,只用更新paddingTop的值就行了
                        }
                    }
                    // 还没有到达显示松开刷新的时候,DONE或者是PULL_To_REFRESH状态
                    if (mPullRefreshState == PULL_To_REFRESH) {
                        setSelection(0);
                        // 下拉到可以进入松开U刷新的状态
                        if ((tempY - startY) / RATIO >= mHeaderHight) {
                            mPullRefreshState = RELEASE_To_REFRESH;
                            isBack = true;
                            changeHeaderViewByState();
                            Log.v(TAG, "由Done或者下拉刷新状态转变到松开刷新");
                        }else if (tempY - startY <= 0) {// 上推到顶了
                            mPullRefreshState = DONE;
                            changeHeaderViewByState();
                            Log.v(TAG, "由Done或者下拉刷新状态转变到Done状态");
                        }
                    }
                    // done状态下
                    if (mPullRefreshState == DONE) {
                        if (tempY - startY > 0) {
                            mPullRefreshState = PULL_To_REFRESH;
                            changeHeaderViewByState();
                        }
                    }
                    // 更新mHeaderLayout的size
                    if (mPullRefreshState == PULL_To_REFRESH) {
                        mHeaderLayout.setPadding(0, -1 * mHeaderHight + (tempY - startY) / RATIO, 0, 0);
                        // mHeaderLayout.setPadding(0, (tempY - startY) / RATIO, 0, 0);
                    }
                    // 更新mHeaderLayout的paddingTop
                    if (mPullRefreshState == RELEASE_To_REFRESH) {
                        mHeaderLayout.setPadding(0, (tempY - startY) / RATIO - mHeaderHight, 0, 0);
                        // mHeaderLayout.setPadding(0, (tempY - startY) / RATIO, 0, 0);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                if (mPullRefreshState != REFRESHING) {
                    if (mPullRefreshState == DONE) {
                        // 正常状态下无需做任何操作
                    }
                    if (mPullRefreshState == PULL_To_REFRESH) {
                        mPullRefreshState = DONE;
                        changeHeaderViewByState();
                        Log.v(TAG, "由下拉刷新状态,到Done状态");
                    }
                    if (mPullRefreshState == RELEASE_To_REFRESH) {
                        mPullRefreshState = REFRESHING;
                        changeHeaderViewByState();
                        refreshListView();
                        Log.v(TAG, "由松开刷新状态,到的Done状态");
                    }
                }
                isRecored = false;
                isBack = false;
                break;
        }
        return super.onTouchEvent(event);
    }

    // 当状态改变时候,调用该方法,以更新界面
    private void changeHeaderViewByState() {
        switch (mPullRefreshState) {
            case RELEASE_To_REFRESH:
                arrowImageView.setVisibility(View.VISIBLE);
                progressBar.setVisibility(View.GONE);
                tipTextView.setVisibility(View.VISIBLE);
                lastUpdatedTextView.setVisibility(View.VISIBLE);

                arrowImageView.clearAnimation();
                arrowImageView.startAnimation(animation);
                tipTextView.setText("松开刷新");
                 Log.v(TAG, "当前状态,松开刷新");
                break;
            case PULL_To_REFRESH:
                progressBar.setVisibility(View.GONE);
                tipTextView.setVisibility(View.VISIBLE);
                lastUpdatedTextView.setVisibility(View.VISIBLE);
                arrowImageView.clearAnimation();
                arrowImageView.setVisibility(View.VISIBLE);
                // 是由RELEASE_To_REFRESH状态转变来的
                if (isBack) {
                    isBack = false;
                    arrowImageView.clearAnimation();
                    arrowImageView.startAnimation(reverseAnimation);
                    tipTextView.setText("下拉刷新");
                } else {
                    tipTextView.setText("下拉刷新");
                }
                  Log.v(TAG, "当前状态,下拉刷新");
                break;
            case REFRESHING:
                // mHeaderLayout.setPadding(0, 0, 0, 0);
                new Thread() {
                    public void run() {
                        while (mHeaderLayout.getPaddingTop() > 1) {
                            Message msg = hand.obtainMessage();
                            msg.what = 1;
                            hand.sendMessage(msg);
                            try {
                                sleep(10);// 慢一点反弹,别一下子就弹回去了
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                }.start();
                progressBar.setVisibility(View.VISIBLE);
                arrowImageView.clearAnimation();
                arrowImageView.setVisibility(View.GONE);
                tipTextView.setText("正在刷新...");
                lastUpdatedTextView.setVisibility(View.VISIBLE);
                Log.v(TAG, "当前状态,正在刷新...");
                break;
            case DONE:
                // mHeaderLayout.setPadding(0, -1 * mHeaderHight, 0, 0);
                new Thread() {
                    public void run() {
                        while (mHeaderLayout.getPaddingTop() > -1 * mHeaderHight) {
                            Message msg = hand.obtainMessage();
                            msg.what = 2;
                            hand.sendMessage(msg);
                            try {
                                sleep(10);// 慢一点反弹,别一下子就弹回去了
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                }.start();
                progressBar.setVisibility(View.GONE);
                arrowImageView.clearAnimation();
                arrowImageView.setImageResource(R.drawable.refresh_list_pull_down);
                tipTextView.setText("下拉刷新");
                lastUpdatedTextView.setVisibility(View.VISIBLE);
                Log.v(TAG, "当前状态,done");
                break;
        }
    }

    private Handler hand = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mPullRefreshState = DONE;
                    lastUpdatedTextView.setText("更新于:"
                            + new Date().toLocaleString());
                    changeHeaderViewByState();
                    break;
                case 1:
                    mHeaderLayout.setPadding(mHeaderLayout.getPaddingLeft(),
                            (int) (mHeaderLayout.getPaddingTop() * 0.75f),
                            mHeaderLayout.getPaddingRight(),
                            mHeaderLayout.getPaddingBottom());
                    break;
                case 2:
                    int top;
                    if (mHeaderLayout.getPaddingTop() >= 0) {
                        top = (int) (-mHeaderHight * 0.25);
                    } else {
                        top = (int) (mHeaderLayout.getPaddingTop() * 1.25f);
                    }
                    mHeaderLayout.setPadding(mHeaderLayout.getPaddingLeft(), top,
                            mHeaderLayout.getPaddingRight(),
                            mHeaderLayout.getPaddingBottom());
                    break;
                default:
                    break;
            }
        };
    };

    // 更新数据,并刷新列表
    private void refreshListView() {
        if (mRefreshListener != null) {
            new Thread() {
                public void run() {
                    try {
                        if (mRefreshListener != null) {
                            Object mRefreshObject = mRefreshListener
                                    .refreshing();
                            sleep(2000);
                            Message msg = hand.obtainMessage();
                            msg.what = 0;
                            msg.obj = mRefreshObject;
                            hand.sendMessage(msg);
                        }
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }// 处理后台加载数据
                };
            }.start();
        }
    }
}

 以下是布局文件:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation='vertical'>
    <include layout="@layout/main_head"/>
    <com.yzj.listview.PullToRefreshListView
            android:id="@+id/bodyList"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:cacheColorHint="#00000000"
            android:fadingEdge="none"
            />
</LinearLayout>

 main_head.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="48dp"
                android:background="@drawable/title">

    <TextView
            android:id="@+id/document_title_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="@string/app_name"
            android:textSize="20sp"
            android:textColor="@android:color/white"
            />
    </RelativeLayout>

 pull_to_refresh_header.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:orientation="horizontal"
              android:background="@android:color/white"
              android:gravity="center">

    <RelativeLayout
            android:layout_width="58dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="-30dp">
        <ImageView
                android:id="@+id/head_imageView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:contentDescription="@string/app_name"
                android:src="@drawable/refresh_list_pull_down"
                />
        <ProgressBar
                android:id="@+id/head_progressBar"
                android:layout_width="28dp"
                android:layout_height="28dp"
                style="?android:attr/progressBarStyleSmall"
                android:layout_centerInParent="true"
                android:visibility="gone"
                />
    </RelativeLayout>
    <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="58dp"
            android:orientation="vertical"
            android:gravity="center">
        <TextView
                android:id="@+id/head_tipTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:text="下拉刷新"
                android:textSize="18sp"
                />
        <TextView
                android:id="@+id/head_lastUpdateTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:text="更新于:2013.08.15 14:15"
                android:textSize="14sp"
                />
    </LinearLayout>
</LinearLayout>

 

你可能感兴趣的:(ListView下拉刷新)