使用库文件实现ListView的下拉刷新

ListView的下拉刷新有很多种,个人觉得使用官方提供的库文件更加方便和简单。使用方法如下:

1.在android环境下导入下载的库文件。库文件的下载地址:http://download.csdn.net/download/xuyanhu_jiayou/5037440

2.新建android项目,在xml中代码:
        xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >


            android:id="@+id/lv_pull"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">



3.在activity中:
package com.example.demo;


import java.util.Arrays;
import java.util.LinkedList;


import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;


import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class MainActivity extends Activity{
private PullToRefreshListView myListView;
private LinkedList mListItems;
 private String[] mStrings = {
           "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam",
           "Abondance"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myListView = (PullToRefreshListView)findViewById(R.id.lv_pull);
mListItems = new LinkedList();
        mListItems.addAll(Arrays.asList(mStrings));


        ArrayAdapter adapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, mListItems);


        myListView.setAdapter(adapter);
        myListView.setOnRefreshListener(new OnRefreshListener() {


@Override
public void onRefresh(PullToRefreshBase refreshView) {
// TODO Auto-generated method stub
new GetDataTask().execute();
}
});
}

private class GetDataTask extends AsyncTask {


        @Override
        protected String[] doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return mStrings;
        }


        @Override
        protected void onPostExecute(String[] result) {
            mListItems.addFirst("Added after refresh...");


            // Call onRefreshComplete when the list has been refreshed.
            myListView.onRefreshComplete();


            super.onPostExecute(result);
        }
    }


}

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