android-刷新之二:PullToRefresh

控件来自Github : chrisbanes/Android-PullToRefresh

支持以下控件的上下拉刷新加载:
ListView
ExpandableListView
GridView
WebView
ScrollView
HorizontalScrollView
ViewPager

控件在2013年2月已经不再维护,所以使用上不能直接使用library dependency来添加依赖。

使用方法:

1、新建module,
Markdown

选择Android library

Markdown
2、GitHub上下载此控件,打开文件夹看到如下目录:
Markdown

library就是我们所需要的依赖核心。将library文件夹打开,看到如下:
Markdown

将刚才新建的module的\src\main中三个文件删除,并将红色标记的三个文件复制到\src\main中,注意要将src文件夹重命名为java。

3、将刚才新建的module设置为app的依赖。即可使用PullToRefresh。
Markdown

4、PullToRefresh基本用法:
1、在布局文件中添加PullToRefresh控件,比如PullToRefreshListView;
2、在Activity中,设置监听器OnRefreshListener以响应用户下拉操作;
3、在监听器的onRefresh()方法中执行数据刷新操作,可以通过AsyncTask来实现;
4、在AsyncTask中获取到数据后,记得调用onRefreshComplete()方法通知PullToRefresh控件数据已获取完毕,可以结束刷新操作。

ptr:ptrMode="both" ,意思:上拉和下拉都支持。
可选值为:
disabled(禁用下拉刷新),
pullFromStart(仅支持下拉刷新),
pullFromEnd(仅支持上拉刷新),
both(二者都支持),
manualOnly(只允许手动触发)

ptr:ptrAnimationStyle的取值:flip(翻转动画), rotate(旋转动画) 。 

ptr:ptrDrawable则就是设置图标了。

自定义下拉指示器文本内容等效果,可以在初始化完成mPullRefreshListView后,通过mPullRefreshListView.getLoadingLayoutProxy()可以得到一个ILoadingLayout对象,这个对象可以设置各种指示器中的样式、文本等。

ILoadingLayout startLabels = mPullRefreshListView  
                .getLoadingLayoutProxy();  
        startLabels.setPullLabel("你可劲拉,拉...");// 刚下拉时,显示的提示  
        startLabels.setRefreshingLabel("好嘞,正在刷新...");// 刷新时  
        startLabels.setReleaseLabel("你敢放,我就敢刷新...");// 下来达到一定距离时,显示的提示 

其他:

ptrRefreshableViewBackground 
//设置整个mPullRefreshListView的背景色
ptrHeaderBackground 
//设置下拉Header或者上拉Footer的背景色
ptrHeaderTextColor 
//用于设置Header与Footer中文本的颜色
ptrHeaderSubTextColor 
//用于设置Header与Footer中上次刷新时间的颜色
ptrShowIndicator
//如果为true会在mPullRefreshListView中出现icon,右上角和右下角,挺有意思的。
ptrHeaderTextAppearance , 
//ptrSubHeaderTextAppearance分别设置拉Header或者上拉Footer中字体的类型颜色等等。
ptrRotateDrawableWhilePulling
//当动画设置为rotate时,下拉是是否旋转。
ptrScrollingWhileRefreshingEnabled
//刷新的时候,是否允许ListView或GridView滚动。觉得为true比较好。
ptrListViewExtrasEnabled 
//决定了Header,Footer以何种方式加入mPullRefreshListView,
//true为headView方式加入,就是滚动时刷新头部会一起滚动。

PullToRefreshListView示例:

布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.administrator.myapplication.MainActivity">

    <com.handmark.pulltorefresh.library.PullToRefreshListView
        xmlns:ptr="http://schemas.android.com/apk/res-auto"
        android:id="@+id/pull_refresh_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:cacheColorHint="#00000000"
        android:divider="#19000000"
        android:dividerHeight="4dp"
        android:fadingEdge="none"
        android:fastScrollEnabled="false"
        android:footerDividersEnabled="false"
        android:headerDividersEnabled="false"
        android:smoothScrollbar="true"
        ptr:ptrMode="both">

    </com.handmark.pulltorefresh.library.PullToRefreshListView>
</RelativeLayout>

Java代码:

package com.example.administrator.myapplication;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

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

public class MainActivity extends AppCompatActivity {
    private LinkedList<String> mListItems;
    /**
     * 上拉刷新的控件
     */
    private PullToRefreshListView mPullRefreshListView;

    private ArrayAdapter<String> mAdapter;

    private int mItemCount = 9;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 得到控件
        mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
        //初始化数据
        initDatas();
        //设置适配器
        mAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, mListItems);
        mPullRefreshListView.setAdapter(mAdapter);
        // 设置监听事件
        mPullRefreshListView
                .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                    @Override
                    public void onPullDownToRefresh(
                            PullToRefreshBase<ListView> refreshView) {
                        Log.e("TAG", "onPullDownToRefresh");
                        String label = DateUtils.formatDateTime(
                                getApplicationContext(),
                                System.currentTimeMillis(),
                                DateUtils.FORMAT_SHOW_TIME
                                        | DateUtils.FORMAT_SHOW_DATE
                                        | DateUtils.FORMAT_ABBREV_ALL);
                        // 显示最后更新的时间
                        refreshView.getLoadingLayoutProxy()
                                .setLastUpdatedLabel(label);

                        //这里写下拉刷新的任务
                        new GetDataTask().execute();
                    }

                    @Override
                    public void onPullUpToRefresh(
                            PullToRefreshBase<ListView> refreshView) {
                        Log.e("TAG", "onPullUpToRefresh");
                        String label = DateUtils.formatDateTime(
                                getApplicationContext(),
                                System.currentTimeMillis(),
                                DateUtils.FORMAT_SHOW_TIME
                                        | DateUtils.FORMAT_SHOW_DATE
                                        | DateUtils.FORMAT_ABBREV_ALL);
                        // 显示最后更新的时间
                        refreshView.getLoadingLayoutProxy()
                                .setLastUpdatedLabel(label);

                        //这里写上拉加载更多的任务
                        new GetDataTask().execute();
                    }
                });

    }

    private void initDatas() {
        // 初始化数据和数据源
        mListItems = new LinkedList<String>();

        for (int i = 0; i < mItemCount; i++) {
            mListItems.add("" + i);
        }
    }

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

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            return "" + (mItemCount++);
        }

        @Override
        protected void onPostExecute(String result) {
            mListItems.add(result);
            mAdapter.notifyDataSetChanged();
            // Call onRefreshComplete when the list has been refreshed.
            mPullRefreshListView.onRefreshComplete();
        }
    }
}

PullToRefreshGridView示例:

布局

activity_ptr_grid.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" >

    <!-- The PullToRefreshGridView replaces a standard GridView widget. -->

    <com.handmark.pulltorefresh.library.PullToRefreshGridView
        xmlns:ptr="http://schemas.android.com/apk/res-auto"
        android:id="@+id/pull_refresh_grid"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="100dp"
        android:gravity="center_horizontal"
        android:horizontalSpacing="1dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:verticalSpacing="1dp"
        ptr:ptrDrawable="@mipmap/ic_launcher"
        ptr:ptrMode="both" />

</LinearLayout>

grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/id_grid_item_text"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="#000000"
    android:gravity="center"
    android:textColor="#ffffff"
    android:textSize="16sp" />

java代码:

package com.example.administrator.myapplication;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateUtils;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.GridView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;

import java.util.LinkedList;

/**
 * Created by Administrator on 2017/5/11.
 */

public class PullToRefreshGridActivity extends AppCompatActivity {
    private LinkedList<String> mListItems;
    private PullToRefreshGridView mPullRefreshListView;
    private ArrayAdapter<String> mAdapter;

    private int mItemCount = 10;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ptr_grid);
        // 得到控件
        mPullRefreshListView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);

        // 初始化数据和数据源
        initDatas();

        mAdapter = new ArrayAdapter<String>(this, R.layout.grid_item,
                R.id.id_grid_item_text, mListItems);
        mPullRefreshListView.setAdapter(mAdapter);

        mPullRefreshListView
                .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {

                    @Override
                    public void onPullDownToRefresh(
                            PullToRefreshBase<GridView> refreshView) {
                        Log.e("TAG", "onPullDownToRefresh"); // Do work to
                        String label = DateUtils.formatDateTime(
                                getApplicationContext(),
                                System.currentTimeMillis(),
                                DateUtils.FORMAT_SHOW_TIME
                                        | DateUtils.FORMAT_SHOW_DATE
                                        | DateUtils.FORMAT_ABBREV_ALL);

                        // Update the LastUpdatedLabel
                        refreshView.getLoadingLayoutProxy()
                                .setLastUpdatedLabel(label);

                        new GetDataTask().execute();
                    }

                    @Override
                    public void onPullUpToRefresh(
                            PullToRefreshBase<GridView> refreshView) {
                        Log.e("TAG", "onPullUpToRefresh"); // Do work to refresh
                        // the list here.
                        new GetDataTask().execute();
                    }
                });
    }

    private void initDatas() {
        mListItems = new LinkedList<String>();

        for (int i = 0; i < mItemCount; i++) {
            mListItems.add(i + "");
        }
    }

    private class GetDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            mListItems.add("" + mItemCount++);
            mAdapter.notifyDataSetChanged();
            // Call onRefreshComplete when the list has been refreshed.
            mPullRefreshListView.onRefreshComplete();
        }
    }
}

参考:

Android PullToRefresh (ListView GridView 下拉刷新) 使用详解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值