[Android]滑动刷新ListView——android-pulltorefresh使用方法解析

    如今不少android应用程序,好比新浪微博,在联网刷新内容时,都有一个滑动刷新的ListView,用户将内容下滑,就会有新的结果呈现。以下图所示:java

    

上图中的功能是一个开源的项目android-pulltorefresh来实现的,咱们能够利用这个项目来完成这个功能。android

这个项目的源码托管在github上,地址为:https://github.com/johannilsson/android-pulltorefreshgit

下面来介绍如何使用:github

滑动刷新其实就用到一个类PullToRefreshListView,它是ListView的子类,相应用到的layout文件为pull_to_refresh_header.xml。也就是说要用滑动刷新,须要将上面的类和xml及一些图片下载下来放到本身的工程中调用。ide

咱们在用到这个类的activity的layout中加上以下代码:code

<!--
  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"
    />

在activity中加入下面的代码:

// 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.
        new GetDataTask().execute();
    }
});

private class GetDataTask extends AsyncTask<Void, Void, String[]> {
    ...
    @Override
    protected void onPostExecute(String[] result) {
        mListItems.addFirst("Added after refresh...");
        // Call onRefreshComplete when the list has been refreshed.
        ((PullToRefreshListView) getListView()).onRefreshComplete();
        super.onPostExecute(result);
    }
}

以上代码分别是设置刷新监听器和后台任务执行。

本身原来写了一个例子,不当心删除了,就不重写贴给你们了。xml

另外,我的感受这个滑动如今不是很灵敏,有些卡。图片

相关文章
相关标签/搜索