使用庫文件實現ListView的下拉刷新

ListView的下拉刷新有很多種,個人覺得使用官方提供的庫文件更加方便和簡單。使用方法如下:

1.在android環境下導入下載的庫文件。庫文件的下載地址:http://download.csdn.net/download/xuyanhu_jiayou/5037440

2.新建android項目,在xml中代碼:
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >


    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/lv_pull"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></com.handmark.pulltorefresh.library.PullToRefreshListView>


</RelativeLayout>
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<String> 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<String>();
        mListItems.addAll(Arrays.asList(mStrings));


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


        myListView.setAdapter(adapter);
        myListView.setOnRefreshListener(new OnRefreshListener<ListView>() {


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

private class GetDataTask extends AsyncTask<Void, Void, String[]> {


        @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);
        }
    }


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章