1

Android下拉刷新上拉加载控件,对所有View通用!

转载http://blog.csdn.net/zhongkejingwang/article/details/38868463

前面写过一篇关于下拉刷新控件的博客下拉刷新控件终结者:PullToRefreshLayout,后来看到好多人还有上拉加载更多的需求,于是就在前面下拉刷新控件的基础上进行了改进,加了上拉加载的功能。不仅如此,我已经把它改成了对所有View都通用!可以随心所欲使用这两个功能~~

我做了一个大集合的demo,实现了ListView、GridView、ExpandableListView、ScrollView、WebView、ImageView、TextView的下拉刷新和上拉加载。后面会提供demo的下载地址。(csdn上的demo有小bug,最新代码已上传到github:https://github.com/jingchenUSTC/PullToRefreshAndLoad)

依照惯例,下面将会是一大波效果图:

demo首页也是可下拉的ListView,在底下可以加入table:

ListView:

GridView:

ExpandableListView:

ScrollView:

WebView:

ImageView:

TextView:

很不错吧?最后的ImageView和TextView是最简单的,直接在下面的接口方法里返回true。

增加上拉加载很简单,和管理下拉头一样,再多管理一个上拉头,也不费事;至于把它改成通用的就需要统一一下View的行为了,为此,我定义了这样一个接口:

[java] view plain copy

  1. package com.jingchen.pulltorefresh.pullableview;
  2. public interface Pullable
  3. {
  4.     /**
  5.      * 判断是否可以下拉,如果不需要下拉功能可以直接return false
  6.      * 
  7.      * @return true如果可以下拉否则返回false
  8.      */
  9.     boolean canPullDown();
  10.     /**
  11.      * 判断是否可以上拉,如果不需要上拉功能可以直接return false
  12.      * 
  13.      * @return true如果可以上拉否则返回false
  14.      */
  15.     boolean canPullUp();
  16. }

从接口名就可以看出它是一个提供判断是否可拉的方法的接口。这个接口的两个方法,canPullDown()是判断何时可以下拉的方法,canPullUp()则是判断何时可以上拉,我在demo中的判断是滑到顶部的时候可以下拉,滑到底部的时候可以上拉。所有需要上拉和下拉的View都需要实现这个接口。后面会给出一些View的实现。先来看看改进后的自定义的布局PullToRefreshLayout,增加了一个上拉头,下拉头和上拉头之间的View是实现了Pullable接口的pullableView。相比前面的版本,这里有改动的需要注意的地方如下:1、增加了上拉头,相应的也增加了控制变量。

2、拉动时消除content_view事件防止误触发不再使用反射,直接设置                       event.setAction(MotionEvent.ACTION_CANCEL)。

3、消除了拉动过程中的多点触碰导致的剧变。

4、不再设置content_view的onTouListener,让使用者可以更加自由的设置监听器。

这个PullToRefreshLayout只负责管理三个控件,如果一个View需要有上拉下拉功能则只需实现接口就行了。下面看PullToRefreshLayout的代码,注释写了好多:

[java] view plain copy

  1. package com.jingchen.pulltorefresh;
  2. import java.util.Timer;
  3. import java.util.TimerTask;
  4. import <a href=“http://lib.csdn.net/base/15” class=“replace_word” title=“undefined” target=“_blank” style=“color:#df3434; font-weight:bold;”>android</a>.content.Context;
  5. import android.graphics.Canvas;
  6. import android.graphics.LinearGradient;
  7. import android.graphics.Paint;
  8. import android.graphics.Paint.Style;
  9. import android.graphics.RectF;
  10. import android.graphics.Shader.TileMode;
  11. import android.os.Handler;
  12. import android.os.Message;
  13. import android.util.AttributeSet;
  14. import android.util.Log;
  15. import android.view.MotionEvent;
  16. import android.view.View;
  17. import android.view.ViewGroup;
  18. import android.view.animation.AnimationUtils;
  19. import android.view.animation.LinearInterpolator;
  20. import android.view.animation.RotateAnimation;
  21. import android.widget.RelativeLayout;
  22. import android.widget.TextView;
  23. import com.jingchen.pulltorefresh.pullableview.Pullable;
  24. /**
  25.  * 自定义的布局,用来管理三个子控件,其中一个是下拉头,一个是包含内容的pullableView(可以是实现Pullable接口的的任何View),
  26.  * 还有一个上拉头
  27.  * 
  28.  * @author 陈靖
  29.  */
  30. public class PullToRefreshLayout extends RelativeLayout
  31. {
  32.     public static final String TAG = “PullToRefreshLayout”;
  33.     // 初始状态
  34.     public static final int INIT = 0;
  35.     // 释放刷新
  36.     public static final int RELEASE_TO_REFRESH = 1;
  37.     // 正在刷新
  38.     public static final int REFRESHING = 2;
  39.     // 释放加载
  40.     public static final int RELEASE_TO_LOAD = 3;
  41.     // 正在加载
  42.     public static final int LOADING = 4;
  43.     // 操作完毕
  44.     public static final int DONE = 5;
  45.     // 当前状态
  46.     private int state = INIT;
  47.     // 刷新回调接口
  48.     private OnRefreshListener mListener;
  49.     // 刷新成功
  50.     public static final int SUCCEED = 0;
  51.     // 刷新失败
  52.     public static final int FAIL = 1;
  53.     // 按下Y坐标,上一个事件点Y坐标
  54.     private float downY, lastY;
  55.     // 下拉的距离。注意:pullDownY和pullUpY不可能同时不为0
  56.     public float pullDownY = 0;
  57.     // 上拉的距离
  58.     private float pullUpY = 0;
  59.     // 释放刷新的距离
  60.     private float refreshDist = 200;
  61.     // 释放加载的距离
  62.     private float loadmoreDist = 200;
  63.     private MyTimer timer;
  64.     // 回滚速度
  65.     public float MOVE_SPEED = 8;
  66.     // 第一次执行布局
  67.     private boolean isLayout = false;
  68.     // 在刷新过程中滑动操作
  69.     private boolean isTouch = false;
  70.     // 手指滑动距离与下拉头的滑动距离比,中间会随正切函数变化
  71.     private float radio = 2;
  72.     // 下拉箭头的转180°动画
  73.     private RotateAnimation rotateAnimation;
  74.     // 均匀旋转动画
  75.     private RotateAnimation refreshingAnimation;
  76.     // 下拉头
  77.     private View refreshView;
  78.     // 下拉的箭头
  79.     private View pullView;
  80.     // 正在刷新的图标
  81.     private View refreshingView;
  82.     // 刷新结果图标
  83.     private View refreshStateImageView;
  84.     // 刷新结果:成功或失败
  85.     private TextView refreshStateTextView;
  86.     // 上拉头
  87.     private View loadmoreView;
  88.     // 上拉的箭头
  89.     private View pullUpView;
  90.     // 正在加载的图标
  91.     private View loadingView;
  92.     // 加载结果图标
  93.     private View loadStateImageView;
  94.     // 加载结果:成功或失败
  95.     private TextView loadStateTextView;
  96.     // 实现了Pullable接口的View
  97.     private View pullableView;
  98.     // 过滤多点触碰
  99.     private int mEvents;
  100.     // 这两个变量用来控制pull的方向,如果不加控制,当情况满足可上拉又可下拉时没法下拉
  101.     private boolean canPullDown = true;
  102.     private boolean canPullUp = true;
  103.     /**
  104.      * 执行自动回滚的handler
  105.      */
  106.     Handler updateHandler = new Handler()
  107.     {
  108.         @Override
  109.         public void handleMessage(Message msg)
  110.         {
  111.             // 回弹速度随下拉距离moveDeltaY增大而增大
  112.             MOVE_SPEED = (float) (8 + 5 * Math.tan(Math.PI / 2
  113.                     / getMeasuredHeight() * (pullDownY + Math.abs(pullUpY))));
  114.             if (!isTouch)
  115.             {
  116.                 // 正在刷新,且没有往上推的话则悬停,显示”正在刷新…”
  117.                 if (state == REFRESHING && pullDownY <= refreshDist)
  118.                 {
  119.                     pullDownY = refreshDist;
  120.                     timer.cancel();
  121.                 } else if (state == LOADING && -pullUpY <= loadmoreDist)
  122.                 {
  123.                     pullUpY = -loadmoreDist;
  124.                     timer.cancel();
  125.                 }
  126.             }
  127.             if (pullDownY > 0)
  128.                 pullDownY -= MOVE_SPEED;
  129.             else if (pullUpY < 0)
  130.                 pullUpY += MOVE_SPEED;
  131.             if (pullDownY < 0)
  132.             {
  133.                 // 已完成回弹
  134.                 pullDownY = 0;
  135.                 pullView.clearAnimation();
  136.                 // 隐藏下拉头时有可能还在刷新,只有当前状态不是正在刷新时才改变状态
  137.                 if (state != REFRESHING && state != LOADING)
  138.                     changeState(INIT);
  139.                 timer.cancel();
  140.             }
  141.             if (pullUpY > 0)
  142.             {
  143.                 // 已完成回弹
  144.                 pullUpY = 0;
  145.                 pullUpView.clearAnimation();
  146.                 // 隐藏下拉头时有可能还在刷新,只有当前状态不是正在刷新时才改变状态
  147.                 if (state != REFRESHING && state != LOADING)
  148.                     changeState(INIT);
  149.                 timer.cancel();
  150.             }
  151.             // 刷新布局,会自动调用onLayout
  152.             requestLayout();
  153.         }
  154.     };
  155.     public void setOnRefreshListener(OnRefreshListener listener)
  156.     {
  157.         mListener = listener;
  158.     }
  159.     public PullToRefreshLayout(Context context)
  160.     {
  161.         super(context);
  162.         initView(context);
  163.     }
  164.     public PullToRefreshLayout(Context context, AttributeSet attrs)
  165.     {
  166.         super(context, attrs);
  167.         initView(context);
  168.     }
  169.     public PullToRefreshLayout(Context context, AttributeSet attrs, int defStyle)
  170.     {
  171.         super(context, attrs, defStyle);
  172.         initView(context);
  173.     }
  174.     private void initView(Context context)
  175.     {
  176.         timer = new MyTimer(updateHandler);
  177.         rotateAnimation = (RotateAnimation) AnimationUtils.loadAnimation(
  178.                 context, R.anim.reverse_anim);
  179.         refreshingAnimation = (RotateAnimation) AnimationUtils.loadAnimation(
  180.                 context, R.anim.rotating);
  181.         // 添加匀速转动动画
  182.         LinearInterpolator lir = new LinearInterpolator();
  183.         rotateAnimation.setInterpolator(lir);
  184.         refreshingAnimation.setInterpolator(lir);
  185.     }
  186.     private void hide()
  187.     {
  188.         timer.schedule(5);
  189.     }
  190.     /**
  191.      * 完成刷新操作,显示刷新结果。注意:刷新完成后一定要调用这个方法
  192.      */
  193.     /**
  194.      * @param refreshResult
  195.      *            PullToRefreshLayout.SUCCEED代表成功,PullToRefreshLayout.FAIL代表失败
  196.      */
  197.     public void refreshFinish(int refreshResult)
  198.     {
  199.         refreshingView.clearAnimation();
  200.         refreshingView.setVisibility(View.GONE);
  201.         switch (refreshResult)
  202.         {
  203.         case SUCCEED:
  204.             // 刷新成功
  205.             refreshStateImageView.setVisibility(View.VISIBLE);
  206.             refreshStateTextView.setText(R.string.refresh_succeed);
  207.             refreshStateImageView
  208.                     .setBackgroundResource(R.drawable.refresh_succeed);
  209.             break;
  210.         case FAIL:
  211.         default:
  212.             // 刷新失败
  213.             refreshStateImageView.setVisibility(View.VISIBLE);
  214.             refreshStateTextView.setText(R.string.refresh_fail);
  215.             refreshStateImageView
  216.                     .setBackgroundResource(R.drawable.refresh_failed);
  217.             break;
  218.         }
  219.         // 刷新结果停留1秒
  220.         new Handler()
  221.         {
  222.             @Override
  223.             public void handleMessage(Message msg)
  224.             {
  225.                 changeState(DONE);
  226.                 hide();
  227.             }
  228.         }.sendEmptyMessageDelayed(01000);
  229.     }
  230.     /**
  231.      * 加载完毕,显示加载结果。注意:加载完成后一定要调用这个方法
  232.      * 
  233.      * @param refreshResult
  234.      *            PullToRefreshLayout.SUCCEED代表成功,PullToRefreshLayout.FAIL代表失败
  235.      */
  236.     public void loadmoreFinish(int refreshResult)
  237.     {
  238.         loadingView.clearAnimation();
  239.         loadingView.setVisibility(View.GONE);
  240.         switch (refreshResult)
  241.         {
  242.         case SUCCEED:
  243.             // 加载成功
  244.             loadStateImageView.setVisibility(View.VISIBLE);
  245.             loadStateTextView.setText(R.string.load_succeed);
  246.             loadStateImageView.setBackgroundResource(R.drawable.load_succeed);
  247.             break;
  248.         case FAIL:
  249.         default:
  250.             // 加载失败
  251.             loadStateImageView.setVisibility(View.VISIBLE);
  252.             loadStateTextView.setText(R.string.load_fail);
  253.             loadStateImageView.setBackgroundResource(R.drawable.load_failed);
  254.             break;
  255.         }
  256.         // 刷新结果停留1秒
  257.         new Handler()
  258.         {
  259.             @Override
  260.             public void handleMessage(Message msg)
  261.             {
  262.                 changeState(DONE);
  263.                 hide();
  264.             }
  265.         }.sendEmptyMessageDelayed(01000);
  266.     }
  267.     private void changeState(int to)
  268.     {
  269.         state = to;
  270.         switch (state)
  271.         {
  272.         case INIT:
  273.             // 下拉布局初始状态
  274.             refreshStateImageView.setVisibility(View.GONE);
  275.             refreshStateTextView.setText(R.string.pull_to_refresh);
  276.             pullView.clearAnimation();
  277.             pullView.setVisibility(View.VISIBLE);
  278.             // 上拉布局初始状态
  279.             loadStateImageView.setVisibility(View.GONE);
  280.             loadStateTextView.setText(R.string.pullup_to_load);
  281.             pullUpView.clearAnimation();
  282.             pullUpView.setVisibility(View.VISIBLE);
  283.             break;
  284.         case RELEASE_TO_REFRESH:
  285.             // 释放刷新状态
  286.             refreshStateTextView.setText(R.string.release_to_refresh);
  287.             pullView.startAnimation(rotateAnimation);
  288.             break;
  289.         case REFRESHING:
  290.             // 正在刷新状态
  291.             pullView.clearAnimation();
  292.             refreshingView.setVisibility(View.VISIBLE);
  293.             pullView.setVisibility(View.INVISIBLE);
  294.             refreshingView.startAnimation(refreshingAnimation);
  295.             refreshStateTextView.setText(R.string.refreshing);
  296.             break;
  297.         case RELEASE_TO_LOAD:
  298.             // 释放加载状态
  299.             loadStateTextView.setText(R.string.release_to_load);
  300.             pullUpView.startAnimation(rotateAnimation);
  301.             break;
  302.         case LOADING:
  303.             // 正在加载状态
  304.             pullUpView.clearAnimation();
  305.             loadingView.setVisibility(View.VISIBLE);
  306.             pullUpView.setVisibility(View.INVISIBLE);
  307.             loadingView.startAnimation(refreshingAnimation);
  308.             loadStateTextView.setText(R.string.loading);
  309.             break;
  310.         case DONE:
  311.             // 刷新或加载完毕,啥都不做
  312.             break;
  313.         }
  314.     }
  315.     /**
  316.      * 不限制上拉或下拉
  317.      */
  318.     private void releasePull()
  319.     {
  320.         canPullDown = true;
  321.         canPullUp = true;
  322.     }
  323.     /*
  324.      * (非 Javadoc)由父控件决定是否分发事件,防止事件冲突
  325.      * 
  326.      * @see android.view.ViewGroup#dispatchTouchEvent(android.view.MotionEvent)
  327.      */
  328.     @Override
  329.     public boolean dispatchTouchEvent(MotionEvent ev)
  330.     {
  331.         switch (ev.getActionMasked())
  332.         {
  333.         case MotionEvent.ACTION_DOWN:
  334.             downY = ev.getY();
  335.             lastY = downY;
  336.             timer.cancel();
  337.             mEvents = 0;
  338.             releasePull();
  339.             break;
  340.         case MotionEvent.ACTION_POINTER_DOWN:
  341.         case MotionEvent.ACTION_POINTER_UP:
  342.             // 过滤多点触碰
  343.             mEvents = –1;
  344.             break;
  345.         case MotionEvent.ACTION_MOVE:
  346.             if (mEvents == 0)
  347.             {
  348.                 if (((Pullable) pullableView).canPullDown() && canPullDown
  349.                         && state != LOADING)
  350.                 {
  351.                     // 可以下拉,正在加载时不能下拉
  352.                     // 对实际滑动距离做缩小,造成用力拉的感觉
  353.                     pullDownY = pullDownY + (ev.getY() – lastY) / radio;
  354.                     if (pullDownY < 0)
  355.                     {
  356.                         pullDownY = 0;
  357.                         canPullDown = false;
  358.                         canPullUp = true;
  359.                     }
  360.                     if (pullDownY > getMeasuredHeight())
  361.                         pullDownY = getMeasuredHeight();
  362.                     if (state == REFRESHING)
  363.                     {
  364.                         // 正在刷新的时候触摸移动
  365.                         isTouch = true;
  366.                     }
  367.                 } else if (((Pullable) pullableView).canPullUp() && canPullUp
  368.                         && state != REFRESHING)
  369.                 {
  370.                     // 可以上拉,正在刷新时不能上拉
  371.                     pullUpY = pullUpY + (ev.getY() – lastY) / radio;
  372.                     if (pullUpY > 0)
  373.                     {
  374.                         pullUpY = 0;
  375.                         canPullDown = true;
  376.                         canPullUp = false;
  377.                     }
  378.                     if (pullUpY < -getMeasuredHeight())
  379.                         pullUpY = -getMeasuredHeight();
  380.                     if (state == LOADING)
  381.                     {
  382.                         // 正在加载的时候触摸移动
  383.                         isTouch = true;
  384.                     }
  385.                 } else
  386.                     releasePull();
  387.             } else
  388.                 mEvents = 0;
  389.             lastY = ev.getY();
  390.             // 根据下拉距离改变比例
  391.             radio = (float) (2 + 2 * Math.tan(Math.PI / 2 / getMeasuredHeight()
  392.                     * (pullDownY + Math.abs(pullUpY))));
  393.             requestLayout();
  394.             if (pullDownY <= refreshDist
  395. <span style=“white-space:pre”>                    </span>&& (state == RELEASE_TO_REFRESH || state == DONE)) {
  396. <span style=“white-space:pre”>                </span>// 如果下拉距离没达到刷新的距离且当前状态是释放刷新,改变状态为下拉刷新
  397. <span style=“white-space:pre”>                </span>changeState(INIT);
  398. <span style=“white-space:pre”>            </span>}
  399. <span style=“white-space:pre”>            </span>if (pullDownY >= refreshDist && (state == INIT || state == DONE)) {
  400. <span style=“white-space:pre”>                </span>// 如果下拉距离达到刷新的距离且当前状态是初始状态刷新,改变状态为释放刷新
  401. <span style=“white-space:pre”>                </span>changeState(RELEASE_TO_REFRESH);
  402. <span style=“white-space:pre”>            </span>}
  403. <span style=“white-space:pre”>            </span>// 下面是判断上拉加载的,同上,注意pullUpY是负值
  404. <span style=“white-space:pre”>            </span>if (-pullUpY <= loadmoreDist
  405. <span style=“white-space:pre”>                    </span>&& (state == RELEASE_TO_LOAD || state == DONE)) {
  406. <span style=“white-space:pre”>                </span>changeState(INIT);
  407. <span style=“white-space:pre”>            </span>}
  408. <span style=“white-space:pre”>            </span>if (-pullUpY >= loadmoreDist && (state == INIT || state == DONE)) {
  409. <span style=“white-space:pre”>                </span>changeState(RELEASE_TO_LOAD);
  410. <span style=“white-space:pre”>            </span>}
  411.             // 因为刷新和加载操作不能同时进行,所以pullDownY和pullUpY不会同时不为0,因此这里用(pullDownY +
  412.             // Math.abs(pullUpY))就可以不对当前状态作区分了
  413.             if ((pullDownY + Math.abs(pullUpY)) > 8)
  414.             {
  415.                 // 防止下拉过程中误触发长按事件和点击事件
  416.                 ev.setAction(MotionEvent.ACTION_CANCEL);
  417.             }
  418.             break;
  419.         case MotionEvent.ACTION_UP:
  420.             if (pullDownY > refreshDist || -pullUpY > loadmoreDist)
  421.                 // 正在刷新时往下拉(正在加载时往上拉),释放后下拉头(上拉头)不隐藏
  422.                 isTouch = false;
  423.             if (state == RELEASE_TO_REFRESH)
  424.             {
  425.                 changeState(REFRESHING);
  426.                 // 刷新操作
  427.                 if (mListener != null)
  428.                     mListener.onRefresh(this);
  429.             } else if (state == RELEASE_TO_LOAD)
  430.             {
  431.                 changeState(LOADING);
  432.                 // 加载操作
  433.                 if (mListener != null)
  434.                     mListener.onLoadMore(this);
  435.             }
  436.             hide();
  437.         default:
  438.             break;
  439.         }
  440.         // 事件分发交给父类
  441.         super.dispatchTouchEvent(ev);
  442.         return true;
  443.     }
  444.     private void initView()
  445.     {
  446.         // 初始化下拉布局
  447.         pullView = refreshView.findViewById(R.id.pull_icon);
  448.         refreshStateTextView = (TextView) refreshView
  449.                 .findViewById(R.id.state_tv);
  450.         refreshingView = refreshView.findViewById(R.id.refreshing_icon);
  451.         refreshStateImageView = refreshView.findViewById(R.id.state_iv);
  452.         // 初始化上拉布局
  453.         pullUpView = loadmoreView.findViewById(R.id.pullup_icon);
  454.         loadStateTextView = (TextView) loadmoreView
  455.                 .findViewById(R.id.loadstate_tv);
  456.         loadingView = loadmoreView.findViewById(R.id.loading_icon);
  457.         loadStateImageView = loadmoreView.findViewById(R.id.loadstate_iv);
  458.     }
  459.     @Override
  460.     protected void onLayout(boolean changed, int l, int t, int r, int b)
  461.     {
  462.         if (!isLayout)
  463.         {
  464.             // 这里是第一次进来的时候做一些初始化
  465.             refreshView = getChildAt(0);
  466.             pullableView = getChildAt(1);
  467.             loadmoreView = getChildAt(2);
  468.             isLayout = true;
  469.             initView();
  470.             refreshDist = ((ViewGroup) refreshView).getChildAt(0)
  471.                     .getMeasuredHeight();
  472.             loadmoreDist = ((ViewGroup) loadmoreView).getChildAt(0)
  473.                     .getMeasuredHeight();
  474.         }
  475.         // 改变子控件的布局,这里直接用(pullDownY + pullUpY)作为偏移量,这样就可以不对当前状态作区分
  476.         refreshView.layout(0,
  477.                 (int) (pullDownY + pullUpY) – refreshView.getMeasuredHeight(),
  478.                 refreshView.getMeasuredWidth(), (int) (pullDownY + pullUpY));
  479.         pullableView.layout(0, (int) (pullDownY + pullUpY),
  480.                 pullableView.getMeasuredWidth(), (int) (pullDownY + pullUpY)
  481.                         + pullableView.getMeasuredHeight());
  482.         loadmoreView.layout(0,
  483.                 (int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight(),
  484.                 loadmoreView.getMeasuredWidth(),
  485.                 (int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight()
  486.                         + loadmoreView.getMeasuredHeight());
  487.     }
  488.     class MyTimer
  489.     {
  490.         private Handler handler;
  491.         private Timer timer;
  492.         private MyTask mTask;
  493.         public MyTimer(Handler handler)
  494.         {
  495.             this.handler = handler;
  496.             timer = new Timer();
  497.         }
  498.         public void schedule(long period)
  499.         {
  500.             if (mTask != null)
  501.             {
  502.                 mTask.cancel();
  503.                 mTask = null;
  504.             }
  505.             mTask = new MyTask(handler);
  506.             timer.schedule(mTask, 0, period);
  507.         }
  508.         public void cancel()
  509.         {
  510.             if (mTask != null)
  511.             {
  512.                 mTask.cancel();
  513.                 mTask = null;
  514.             }
  515.         }
  516.         class MyTask extends TimerTask
  517.         {
  518.             private Handler handler;
  519.             public MyTask(Handler handler)
  520.             {
  521.                 this.handler = handler;
  522.             }
  523.             @Override
  524.             public void run()
  525.             {
  526.                 handler.obtainMessage().sendToTarget();
  527.             }
  528.         }
  529.     }
  530.     /**
  531.      * 刷新加载回调接口
  532.      * 
  533.      * @author chenjing
  534.      * 
  535.      */
  536.     public interface OnRefreshListener
  537.     {
  538.         /**
  539.          * 刷新操作
  540.          */
  541.         void onRefresh(PullToRefreshLayout pullToRefreshLayout);
  542.         /**
  543.          * 加载操作
  544.          */
  545.         void onLoadMore(PullToRefreshLayout pullToRefreshLayout);
  546.     }
  547. }

上面就是整个布局的代码,并不是很难。下面看各个View对Pullable接口的实现,ListView和GridView还有ExpandableListView的判断方法是一样的:

PullableListView:

[java] view plain copy

  1. package com.jingchen.pulltorefresh.pullableview;
  2. import android.content.Context;
  3. import android.util.AttributeSet;
  4. import android.util.Log;
  5. import android.widget.ListView;
  6. public class PullableListView extends ListView implements Pullable
  7. {
  8.     public PullableListView(Context context)
  9.     {
  10.         super(context);
  11.     }
  12.     public PullableListView(Context context, AttributeSet attrs)
  13.     {
  14.         super(context, attrs);
  15.     }
  16.     public PullableListView(Context context, AttributeSet attrs, int defStyle)
  17.     {
  18.         super(context, attrs, defStyle);
  19.     }
  20.     @Override
  21.     public boolean canPullDown()
  22.     {
  23.         if (getCount() == 0)
  24.         {
  25.             // 没有item的时候也可以下拉刷新
  26.             return true;
  27.         } else if (getFirstVisiblePosition() == 0
  28.                 && getChildAt(0).getTop() >= 0)
  29.         {
  30.             // 滑到ListView的顶部了
  31.             return true;
  32.         } else
  33.             return false;
  34.     }
  35.     @Override
  36.     public boolean canPullUp()
  37.     {
  38.         if (getCount() == 0)
  39.         {
  40.             // 没有item的时候也可以上拉加载
  41.             return true;
  42.         } else if (getLastVisiblePosition() == (getCount() – 1))
  43.         {
  44.             // 滑到底部了
  45.             if (getChildAt(getLastVisiblePosition() – getFirstVisiblePosition()) != null
  46.                     && getChildAt(
  47.                             getLastVisiblePosition()
  48.                                     – getFirstVisiblePosition()).getBottom() <= getMeasuredHeight())
  49.                 return true;
  50.         }
  51.         return false;
  52.     }
  53. }

PullableExpandableListView:

[java] view plain copy

  1. package com.jingchen.pulltorefresh.pullableview;
  2. import android.content.Context;
  3. import android.util.AttributeSet;
  4. import android.widget.ExpandableListView;
  5. public class PullableExpandableListView extends ExpandableListView implements
  6.         Pullable
  7. {
  8.     public PullableExpandableListView(Context context)
  9.     {
  10.         super(context);
  11.     }
  12.     public PullableExpandableListView(Context context, AttributeSet attrs)
  13.     {
  14.         super(context, attrs);
  15.     }
  16.     public PullableExpandableListView(Context context, AttributeSet attrs,
  17.             int defStyle)
  18.     {
  19.         super(context, attrs, defStyle);
  20.     }
  21.     @Override
  22.     public boolean canPullDown()
  23.     {
  24.         if (getCount() == 0)
  25.         {
  26.             // 没有item的时候也可以下拉刷新
  27.             return true;
  28.         } else if (getFirstVisiblePosition() == 0
  29.                 && getChildAt(0).getTop() >= 0)
  30.         {
  31.             // 滑到顶部了
  32.             return true;
  33.         } else
  34.             return false;
  35.     }
  36.     @Override
  37.     public boolean canPullUp()
  38.     {
  39.         if (getCount() == 0)
  40.         {
  41.             // 没有item的时候也可以上拉加载
  42.             return true;
  43.         } else if (getLastVisiblePosition() == (getCount() – 1))
  44.         {
  45.             // 滑到底部了
  46.             if (getChildAt(getLastVisiblePosition() – getFirstVisiblePosition()) != null
  47.                     && getChildAt(
  48.                             getLastVisiblePosition()
  49.                                     – getFirstVisiblePosition()).getBottom() <= getMeasuredHeight())
  50.                 return true;
  51.         }
  52.         return false;
  53.     }
  54. }

PullableGridView:

[java] view plain copy

  1. package com.jingchen.pulltorefresh.pullableview;
  2. import android.content.Context;
  3. import android.util.AttributeSet;
  4. import android.widget.GridView;
  5. public class PullableGridView extends GridView implements Pullable
  6. {
  7.     public PullableGridView(Context context)
  8.     {
  9.         super(context);
  10.     }
  11.     public PullableGridView(Context context, AttributeSet attrs)
  12.     {
  13.         super(context, attrs);
  14.     }
  15.     public PullableGridView(Context context, AttributeSet attrs, int defStyle)
  16.     {
  17.         super(context, attrs, defStyle);
  18.     }
  19.     @Override
  20.     public boolean canPullDown()
  21.     {
  22.         if (getCount() == 0)
  23.         {
  24.             // 没有item的时候也可以下拉刷新
  25.             return true;
  26.         } else if (getFirstVisiblePosition() == 0
  27.                 && getChildAt(0).getTop() >= 0)
  28.         {
  29.             // 滑到顶部了
  30.             return true;
  31.         } else
  32.             return false;
  33.     }
  34.     @Override
  35.     public boolean canPullUp()
  36.     {
  37.         if (getCount() == 0)
  38.         {
  39.             // 没有item的时候也可以上拉加载
  40.             return true;
  41.         } else if (getLastVisiblePosition() == (getCount() – 1))
  42.         {
  43.             // 滑到底部了
  44.             if (getChildAt(getLastVisiblePosition() – getFirstVisiblePosition()) != null
  45.                     && getChildAt(
  46.                             getLastVisiblePosition()
  47.                                     – getFirstVisiblePosition()).getBottom() <= getMeasuredHeight())
  48.                 return true;
  49.         }
  50.         return false;
  51.     }
  52. }

PullableScrollView:

[java] view plain copy

  1. package com.jingchen.pulltorefresh.pullableview;
  2. import android.content.Context;
  3. import android.util.AttributeSet;
  4. import android.widget.ScrollView;
  5. public class PullableScrollView extends ScrollView implements Pullable
  6. {
  7.     public PullableScrollView(Context context)
  8.     {
  9.         super(context);
  10.     }
  11.     public PullableScrollView(Context context, AttributeSet attrs)
  12.     {
  13.         super(context, attrs);
  14.     }
  15.     public PullableScrollView(Context context, AttributeSet attrs, int defStyle)
  16.     {
  17.         super(context, attrs, defStyle);
  18.     }
  19.     @Override
  20.     public boolean canPullDown()
  21.     {
  22.         if (getScrollY() == 0)
  23.             return true;
  24.         else
  25.             return false;
  26.     }
  27.     @Override
  28.     public boolean canPullUp()
  29.     {
  30.         if (getScrollY() >= (getChildAt(0).getHeight() – getMeasuredHeight()))
  31.             return true;
  32.         else
  33.             return false;
  34.     }
  35. }

PullableWebView:

[java] view plain copy

  1. package com.jingchen.pulltorefresh.pullableview;
  2. import android.content.Context;
  3. import android.util.AttributeSet;
  4. import android.webkit.WebView;
  5. public class PullableWebView extends WebView implements Pullable
  6. {
  7.     public PullableWebView(Context context)
  8.     {
  9.         super(context);
  10.     }
  11.     public PullableWebView(Context context, AttributeSet attrs)
  12.     {
  13.         super(context, attrs);
  14.     }
  15.     public PullableWebView(Context context, AttributeSet attrs, int defStyle)
  16.     {
  17.         super(context, attrs, defStyle);
  18.     }
  19.     @Override
  20.     public boolean canPullDown()
  21.     {
  22.         if (getScrollY() == 0)
  23.             return true;
  24.         else
  25.             return false;
  26.     }
  27.     @Override
  28.     public boolean canPullUp()
  29.     {
  30.         if (getScrollY() >= getContentHeight() * getScale()
  31.                 – getMeasuredHeight())
  32.             return true;
  33.         else
  34.             return false;
  35.     }
  36. }

ImageView和TextView就不贴了,我直接在方法里返回了true。OK了,整个demo的代码有点多,就不贴了。

源码下载

天边的星星