分享

ListView下拉刷新,上拉自动加载更多

 淡淡的痴呆 2014-08-08

下拉刷新,Android中非常普遍的功能。为了方便便重写的ListView来实现下拉刷新,同时添加了上拉自动加载更多的功能。设计最初是参考开源中国的Android客户端源码。先看示例图。

        

                                                  图1                                                                                                             图2


        

                                                  图3                                                                                                            图4


         

                                                  图5                                                                                                       图6

下拉刷新的时动画效果: 图1 ==》 图2 ==》 图3 ==》 图4 ==》 图1。

上拉自动加载更多的效果:图5

图6是示例demo的截图

重写后的listview动画效果来源于添加的头部(header)和尾部(footer),listview提供了addHeaderView和addFooterView方法来添加header和footer。大家也可以通过修改头部、尾部的xml文件来定义自己的动画效果。


实现原理

1.下拉刷新

通过onTouchEvent判断手势,来改变listview的header。header的状态共4种,自己定义为:

NONE(对应图1):初始状态

PULL(对应图2):下拉状态,此时松开会还原到状态NONE,并不进行刷新

RELEASE(对应图3):同样是下拉状态,但此刻松开会执行刷新,进入状态REFRESHING

REFRESHING(对应图4):正在执行刷新,刷新结束后进入状态NONE。

header在四种状态切换时不仅改变内部组件,同时改变自身的大小。改变内部组件的体现比如,箭头的朝上或者朝下,文字提示的变化,等待圆圈的显示与否。大小的改变其实就是高度的改变,NONE时header高度为0,RELEASE时header的高度由你下拉的程度决定。

2.加载更多

在listview滑动停止后,判断listview的最后一个item是否已经显示,如果显示说明listview已经滑动到了最底部,这时便触发加载更多的方法,方法结束根据结果改变footer。

3.回调方法

在类中定义了两个接口OnRefreshListener和OnLoadListener,用来定义和提供加载数据的方法,具体实现则交给它们的实现类去做。


示例代码

AutoListView.java

  1. package com.example.autolistview.widget;  
  2.   
  3. import com.example.autolistview.R;  
  4. import com.example.autolistview.utils.Utils;  
  5.   
  6. import android.content.Context;  
  7. import android.util.AttributeSet;  
  8. import android.view.LayoutInflater;  
  9. import android.view.MotionEvent;  
  10. import android.view.View;  
  11. import android.view.ViewGroup;  
  12. import android.view.animation.LinearInterpolator;  
  13. import android.view.animation.RotateAnimation;  
  14. import android.widget.AbsListView;  
  15. import android.widget.ImageView;  
  16. import android.widget.ProgressBar;  
  17. import android.widget.TextView;  
  18. import android.widget.AbsListView.OnScrollListener;  
  19. import android.widget.ListView;  
  20.   
  21. /** 
  22.  * @author SunnyCoffee 
  23.  * @create 2013-10-24 
  24.  * @version 1.0 
  25.  * @desc 自定义Listview 下拉刷新,上拉加载更多 
  26.  */  
  27.   
  28. public class AutoListView extends ListView implements OnScrollListener {  
  29.   
  30.     // 区分当前操作是刷新还是加载  
  31.     public static final int REFRESH = 0;  
  32.     public static final int LOAD = 1;  
  33.   
  34.     // 区分PULL和RELEASE的距离的大小  
  35.     private static final int SPACE = 20;  
  36.   
  37.     // 定义header的四种状态和当前状态  
  38.     private static final int NONE = 0;  
  39.     private static final int PULL = 1;  
  40.     private static final int RELEASE = 2;  
  41.     private static final int REFRESHING = 3;  
  42.     private int state;  
  43.   
  44.     private LayoutInflater inflater;  
  45.     private View header;  
  46.     private View footer;  
  47.     private TextView tip;  
  48.     private TextView lastUpdate;  
  49.     private ImageView arrow;  
  50.     private ProgressBar refreshing;  
  51.   
  52.     private TextView noData;  
  53.     private TextView loadFull;  
  54.     private TextView more;  
  55.     private ProgressBar loading;  
  56.   
  57.     private RotateAnimation animation;  
  58.     private RotateAnimation reverseAnimation;  
  59.   
  60.     private int startY;  
  61.   
  62.     private int firstVisibleItem;  
  63.     private int scrollState;  
  64.     private int headerContentInitialHeight;  
  65.     private int headerContentHeight;  
  66.   
  67.     // 只有在listview第一个item显示的时候(listview滑到了顶部)才进行下拉刷新, 否则此时的下拉只是滑动listview  
  68.     private boolean isRecorded;  
  69.     private boolean isLoading;// 判断是否正在加载  
  70.     private boolean loadEnable = true;// 开启或者关闭加载更多功能  
  71.     private boolean isLoadFull;  
  72.     private int pageSize = 10;  
  73.   
  74.     private OnRefreshListener onRefreshListener;  
  75.     private OnLoadListener onLoadListener;  
  76.   
  77.     public AutoListView(Context context) {  
  78.         super(context);  
  79.         initView(context);  
  80.     }  
  81.   
  82.     public AutoListView(Context context, AttributeSet attrs) {  
  83.         super(context, attrs);  
  84.         initView(context);  
  85.     }  
  86.   
  87.     public AutoListView(Context context, AttributeSet attrs, int defStyle) {  
  88.         super(context, attrs, defStyle);  
  89.         initView(context);  
  90.     }  
  91.   
  92.     // 下拉刷新监听  
  93.     public void setOnRefreshListener(OnRefreshListener onRefreshListener) {  
  94.         this.onRefreshListener = onRefreshListener;  
  95.     }  
  96.   
  97.     // 加载更多监听  
  98.     public void setOnLoadListener(OnLoadListener onLoadListener) {  
  99.         this.loadEnable = true;  
  100.         this.onLoadListener = onLoadListener;  
  101.     }  
  102.   
  103.     public boolean isLoadEnable() {  
  104.         return loadEnable;  
  105.     }  
  106.   
  107.     // 这里的开启或者关闭加载更多,并不支持动态调整  
  108.     public void setLoadEnable(boolean loadEnable) {  
  109.         this.loadEnable = loadEnable;  
  110.         this.removeFooterView(footer);  
  111.     }  
  112.   
  113.     public int getPageSize() {  
  114.         return pageSize;  
  115.     }  
  116.   
  117.     public void setPageSize(int pageSize) {  
  118.         this.pageSize = pageSize;  
  119.     }  
  120.   
  121.     // 初始化组件  
  122.     private void initView(Context context) {  
  123.   
  124.         // 设置箭头特效  
  125.         animation = new RotateAnimation(0, -180,  
  126.                 RotateAnimation.RELATIVE_TO_SELF, 0.5f,  
  127.                 RotateAnimation.RELATIVE_TO_SELF, 0.5f);  
  128.         animation.setInterpolator(new LinearInterpolator());  
  129.         animation.setDuration(100);  
  130.         animation.setFillAfter(true);  
  131.   
  132.         reverseAnimation = new RotateAnimation(-180, 0,  
  133.                 RotateAnimation.RELATIVE_TO_SELF, 0.5f,  
  134.                 RotateAnimation.RELATIVE_TO_SELF, 0.5f);  
  135.         reverseAnimation.setInterpolator(new LinearInterpolator());  
  136.         reverseAnimation.setDuration(100);  
  137.         reverseAnimation.setFillAfter(true);  
  138.   
  139.         inflater = LayoutInflater.from(context);  
  140.         footer = inflater.inflate(R.layout.listview_footer, null);  
  141.         loadFull = (TextView) footer.findViewById(R.id.loadFull);  
  142.         noData = (TextView) footer.findViewById(R.id.noData);  
  143.         more = (TextView) footer.findViewById(R.id.more);  
  144.         loading = (ProgressBar) footer.findViewById(R.id.loading);  
  145.   
  146.         header = inflater.inflate(R.layout.pull_to_refresh_header, null);  
  147.         arrow = (ImageView) header.findViewById(R.id.arrow);  
  148.         tip = (TextView) header.findViewById(R.id.tip);  
  149.         lastUpdate = (TextView) header.findViewById(R.id.lastUpdate);  
  150.         refreshing = (ProgressBar) header.findViewById(R.id.refreshing);  
  151.   
  152.         // 为listview添加头部和尾部,并进行初始化  
  153.         headerContentInitialHeight = header.getPaddingTop();  
  154.         measureView(header);  
  155.         headerContentHeight = header.getMeasuredHeight();  
  156.         topPadding(-headerContentHeight);  
  157.         this.addHeaderView(header);  
  158.         this.addFooterView(footer);  
  159.         this.setOnScrollListener(this);  
  160.     }  
  161.   
  162.     public void onRefresh() {  
  163.         if (onRefreshListener != null) {  
  164.             onRefreshListener.onRefresh();  
  165.         }  
  166.     }  
  167.   
  168.     public void onLoad() {  
  169.         if (onLoadListener != null) {  
  170.             onLoadListener.onLoad();  
  171.         }  
  172.     }  
  173.   
  174.     public void onRefreshComplete(String updateTime) {  
  175.         lastUpdate.setText(this.getContext().getString(R.string.lastUpdateTime,  
  176.                 lastUpdate));  
  177.         state = NONE;  
  178.         refreshHeaderViewByState();  
  179.     }  
  180.   
  181.     // 用于下拉刷新结束后的回调  
  182.     public void onRefreshComplete() {  
  183.         String currentTime = Utils.getCurrentTime();  
  184.         onRefreshComplete(currentTime);  
  185.     }  
  186.   
  187.     // 用于加载更多结束后的回调  
  188.     public void onLoadComplete() {  
  189.         isLoading = false;  
  190.     }  
  191.   
  192.     @Override  
  193.     public void onScroll(AbsListView view, int firstVisibleItem,  
  194.             int visibleItemCount, int totalItemCount) {  
  195.         this.firstVisibleItem = firstVisibleItem;  
  196.     }  
  197.   
  198.     @Override  
  199.     public void onScrollStateChanged(AbsListView view, int scrollState) {  
  200.         this.scrollState = scrollState;  
  201.         ifNeedLoad(view, scrollState);  
  202.     }  
  203.   
  204.     // 根据listview滑动的状态判断是否需要加载更多  
  205.     private void ifNeedLoad(AbsListView view, int scrollState) {  
  206.         if (!loadEnable) {  
  207.             return;  
  208.         }  
  209.         try {  
  210.             if (scrollState == OnScrollListener.SCROLL_STATE_IDLE  
  211.                     && !isLoading  
  212.                     && view.getLastVisiblePosition() == view  
  213.                             .getPositionForView(footer) && !isLoadFull) {  
  214.                 onLoad();  
  215.                 isLoading = true;  
  216.             }  
  217.         } catch (Exception e) {  
  218.         }  
  219.     }  
  220.   
  221.     /** 
  222.      * 监听触摸事件,解读手势 
  223.      */  
  224.     @Override  
  225.     public boolean onTouchEvent(MotionEvent ev) {  
  226.         switch (ev.getAction()) {  
  227.         case MotionEvent.ACTION_DOWN:  
  228.             if (firstVisibleItem == 0) {  
  229.                 isRecorded = true;  
  230.                 startY = (int) ev.getY();  
  231.             }  
  232.             break;  
  233.         case MotionEvent.ACTION_CANCEL:  
  234.         case MotionEvent.ACTION_UP:  
  235.             if (state == PULL) {  
  236.                 state = NONE;  
  237.                 refreshHeaderViewByState();  
  238.             } else if (state == RELEASE) {  
  239.                 state = REFRESHING;  
  240.                 refreshHeaderViewByState();  
  241.                 onRefresh();  
  242.             }  
  243.             isRecorded = false;  
  244.             break;  
  245.         case MotionEvent.ACTION_MOVE:  
  246.             whenMove(ev);  
  247.             break;  
  248.         }  
  249.         return super.onTouchEvent(ev);  
  250.     }  
  251.   
  252.     // 解读手势,刷新header状态  
  253.     private void whenMove(MotionEvent ev) {  
  254.         if (!isRecorded) {  
  255.             return;  
  256.         }  
  257.         int tmpY = (int) ev.getY();  
  258.         int space = tmpY - startY;  
  259.         int topPadding = space - headerContentHeight;  
  260.         switch (state) {  
  261.         case NONE:  
  262.             if (space > 0) {  
  263.                 state = PULL;  
  264.                 refreshHeaderViewByState();  
  265.             }  
  266.             break;  
  267.         case PULL:  
  268.             topPadding(topPadding);  
  269.             if (scrollState == SCROLL_STATE_TOUCH_SCROLL  
  270.                     && space > headerContentHeight + SPACE) {  
  271.                 state = RELEASE;  
  272.                 refreshHeaderViewByState();  
  273.             }  
  274.             break;  
  275.         case RELEASE:  
  276.             topPadding(topPadding);  
  277.             if (space > 0 && space < headerContentHeight + SPACE) {  
  278.                 state = PULL;  
  279.                 refreshHeaderViewByState();  
  280.             } else if (space <= 0) {  
  281.                 state = NONE;  
  282.                 refreshHeaderViewByState();  
  283.             }  
  284.             break;  
  285.         }  
  286.   
  287.     }  
  288.   
  289.     // 调整header的大小。其实调整的只是距离顶部的高度。  
  290.     private void topPadding(int topPadding) {  
  291.         header.setPadding(header.getPaddingLeft(), topPadding,  
  292.                 header.getPaddingRight(), header.getPaddingBottom());  
  293.         header.invalidate();  
  294.     }  
  295.   
  296.     /** 
  297.      * 这个方法是根据结果的大小来决定footer显示的。 
  298.      * <p> 
  299.      * 这里假定每次请求的条数为10。如果请求到了10条。则认为还有数据。如过结果不足10条,则认为数据已经全部加载,这时footer显示已经全部加载 
  300.      * </p> 
  301.      *  
  302.      * @param resultSize 
  303.      */  
  304.     public void setResultSize(int resultSize) {  
  305.         if (resultSize == 0) {  
  306.             isLoadFull = true;  
  307.             loadFull.setVisibility(View.GONE);  
  308.             loading.setVisibility(View.GONE);  
  309.             more.setVisibility(View.GONE);  
  310.             noData.setVisibility(View.VISIBLE);  
  311.         } else if (resultSize > 0 && resultSize < pageSize) {  
  312.             isLoadFull = true;  
  313.             loadFull.setVisibility(View.VISIBLE);  
  314.             loading.setVisibility(View.GONE);  
  315.             more.setVisibility(View.GONE);  
  316.             noData.setVisibility(View.GONE);  
  317.         } else if (resultSize == pageSize) {  
  318.             isLoadFull = false;  
  319.             loadFull.setVisibility(View.GONE);  
  320.             loading.setVisibility(View.VISIBLE);  
  321.             more.setVisibility(View.VISIBLE);  
  322.             noData.setVisibility(View.GONE);  
  323.         }  
  324.   
  325.     }  
  326.   
  327.     // 根据当前状态,调整header  
  328.     private void refreshHeaderViewByState() {  
  329.         switch (state) {  
  330.         case NONE:  
  331.             topPadding(-headerContentHeight);  
  332.             tip.setText(R.string.pull_to_refresh);  
  333.             refreshing.setVisibility(View.GONE);  
  334.             arrow.clearAnimation();  
  335.             arrow.setImageResource(R.drawable.pull_to_refresh_arrow);  
  336.             break;  
  337.         case PULL:  
  338.             arrow.setVisibility(View.VISIBLE);  
  339.             tip.setVisibility(View.VISIBLE);  
  340.             lastUpdate.setVisibility(View.VISIBLE);  
  341.             refreshing.setVisibility(View.GONE);  
  342.             tip.setText(R.string.pull_to_refresh);  
  343.             arrow.clearAnimation();  
  344.             arrow.setAnimation(reverseAnimation);  
  345.             break;  
  346.         case RELEASE:  
  347.             arrow.setVisibility(View.VISIBLE);  
  348.             tip.setVisibility(View.VISIBLE);  
  349.             lastUpdate.setVisibility(View.VISIBLE);  
  350.             refreshing.setVisibility(View.GONE);  
  351.             tip.setText(R.string.pull_to_refresh);  
  352.             tip.setText(R.string.release_to_refresh);  
  353.             arrow.clearAnimation();  
  354.             arrow.setAnimation(animation);  
  355.             break;  
  356.         case REFRESHING:  
  357.             topPadding(headerContentInitialHeight);  
  358.             refreshing.setVisibility(View.VISIBLE);  
  359.             arrow.clearAnimation();  
  360.             arrow.setVisibility(View.GONE);  
  361.             tip.setVisibility(View.GONE);  
  362.             lastUpdate.setVisibility(View.GONE);  
  363.             break;  
  364.         }  
  365.     }  
  366.   
  367.     // 用来计算header大小的。比较隐晦。  
  368.     private void measureView(View child) {  
  369.         ViewGroup.LayoutParams p = child.getLayoutParams();  
  370.         if (p == null) {  
  371.             p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,  
  372.                     ViewGroup.LayoutParams.WRAP_CONTENT);  
  373.         }  
  374.         int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);  
  375.         int lpHeight = p.height;  
  376.         int childHeightSpec;  
  377.         if (lpHeight > 0) {  
  378.             childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,  
  379.                     MeasureSpec.EXACTLY);  
  380.         } else {  
  381.             childHeightSpec = MeasureSpec.makeMeasureSpec(0,  
  382.                     MeasureSpec.UNSPECIFIED);  
  383.         }  
  384.         child.measure(childWidthSpec, childHeightSpec);  
  385.     }  
  386.   
  387.     /* 
  388.      * 定义下拉刷新接口 
  389.      */  
  390.     public interface OnRefreshListener {  
  391.         public void onRefresh();  
  392.     }  
  393.   
  394.     /* 
  395.      * 定义加载更多接口 
  396.      */  
  397.     public interface OnLoadListener {  
  398.         public void onLoad();  
  399.     }  
  400.   
  401. }  

这个类的逻辑复杂的地方就是header四种状态的判断和切换。

以下是几种状态的切换情况

NONE   ==》 PULL

NONE 《==   PULL   ==》 RELEASE

PULL 《==   RELEASE   ==》 REFRESHING

REFRESHING   ==》 NONE

代码中对于 RELEASE  ==》PULL 状态的切换处理的不太理想,好像是纵坐标的记录方式有问题,如果有谁解决,希望能够留言告知。


为了减少篇幅,其他代码就不在贴了。

注意:定义header的xml最外层必须使用线性布局,不然的话会出错。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多