码迷,mamicode.com
首页 > 移动开发 > 详细

Android开源项目pulltorefresh分析与简单使用

时间:2014-07-05 10:45:13      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:listview   refresh   

在Android开发中有时我们需要访问网络实时刷新数据,比如QQ好友在线状态最新信息,QQ空间需要显示更多的好友动态信息,EOE论坛客户端显示更多的文章帖子信息等。android-pulltorefresh开源项目提供一个向下滑动即刷新列表的功能,将该项目稍作修改即可应用到自己的项目中。


1.下载地址

https://github.com/johannilsson/android-pulltorefresh

该项目为 Android 应用提供一个向下滑动即刷新列表的功能。


2.工程组成

PullToRefreshListView.java

OnRefreshListener 监听刷新操作的接口 ,onRefresh()刷新函数 在列表头部显示正在进行的刷新操作进度条

onRefreshComplete() 刷新操作完成后,恢复列表常态

上述类和接口的具体实现:

public class PullToRefreshListView extends ListView implements OnScrollListener{

  /**Interface definition for a callback to be invoked when list should be refreshed.
     */
    public interface OnRefreshListener {
        /**
         * Called when the list should be refreshed.
         * <p>
         * A call to {@link PullToRefreshListView #onRefreshComplete()} is expected to indicate that the refresh has completed.
         */
        public void onRefresh();
    }

/**
     * Resets the list to a normal state after a refresh.
     * @param lastUpdated Last updated at.
     */
    public void onRefreshComplete(CharSequence lastUpdated) {
        setLastUpdated(lastUpdated);
        onRefreshComplete();
    }

    /**
     * Resets the list to a normal state after a refresh.
     */
    public void onRefreshComplete() {        
        Log.d(TAG, "onRefreshComplete");
        resetHeader();
// If refresh view is visible when loading completes, scroll down to
// the next item.
        if (getFirstVisiblePosition() == 0) {
            invalidateViews();
            setSelection(1);
        }
    }
}

pull_to_refresh_header.xml

PullToRefreshListView头部 显示刷新进度条信息 ,在 PullToRefreshListView.java调用下面的语句将该子布局添加到列表顶部

private LayoutInflater mInflater;

private RelativeLayout mRefreshView;

 mInflater = (LayoutInflater) context.getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);
//header part of PullToRefreshListView
mRefreshView = (RelativeLayout) mInflater.inflate(R.layout.pull_to_refresh_header, this, false);

 //add header part to the ListView
addHeaderView(mRefreshView);

PullToRefreshActivity.java   (MainActivity)

pull_to_refresh.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <!--
    The PullToRefreshListView replaces a standard ListView widget.
    -->
    <com.markupartist.android.widget.PullToRefreshListView
        android:id="@+id/android:list"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        />
</LinearLayout>
注:

LiveActivity本身继承了关于List操作的众多接口,我们可以方便的重写这些操作中需要的方法来实现自己需要的功能。如果要用ListActivity,则 ActivityLayout文件中必须包括一个(只能一个)ListView,且ListViewid= "@id/android:list"


3.PullToRefreshActivity.java

刷新额外的列表数据String mExtras[],当额外列表数据显示完毕时,不再进行刷新操作。

例如下面这个例子刷新三次以后,就没有额外需要显示的数据,拉松列表进行刷新操作将提示“No More Messages”

package com.markupartist.android.example.pulltorefresh;

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

import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;

@SuppressLint("NewApi")
public class PullToRefreshActivity extends ListActivity {    
    private LinkedList<String> mListItems;
    int count = 0;
    

    /** Called when the activity is first created. */
    @SuppressLint("NewApi")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pull_to_refresh);
        
        // Set a listener to be invoked when the list should be refreshed.
        ((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Do work to refresh the list here.
            	if(count < mExtras.length)
            		new GetDataTask().execute(count++);
            	else{
            		Toast.makeText(getApplicationContext(), "No More Messages", 
            				Toast.LENGTH_LONG).show();
            		
            		//Resets the list to a normal state after a refresh
            		((PullToRefreshListView) getListView()).onRefreshComplete();
            	}
            		
            }
        });

        mListItems = new LinkedList<String>();
        mListItems.addAll(Arrays.asList(mStrings));

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

        setListAdapter(adapter);
    }

    private class GetDataTask extends AsyncTask<Integer, Void, String[]> {
    	
    	private int count;
    	
        @Override
        protected String[] doInBackground(Integer... params) {
        	count = params[0];
        	// Simulates a background job.
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                ;
            }
            return mStrings;
        }

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

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

           // super.onPostExecute(result);
        }
    }

    private String[] mStrings = {
            "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam",
            "Abondance", "Ackawi", "Acorn", "Adelost", "Affidelice au Chablis",
            "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
            "Allgauer Emmentaler"};
    
    private String[] mExtras = {"extra1","extra2","extra3"};
    
}



Android开源项目pulltorefresh分析与简单使用,布布扣,bubuko.com

Android开源项目pulltorefresh分析与简单使用

标签:listview   refresh   

原文地址:http://blog.csdn.net/hishentan/article/details/36706191

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!