Android实战简易教程<五十四>(通过实现OnScrollListener接口实现下拉刷新功能)

来源:互联网 发布:网吧计费软件 编辑:程序博客网 时间:2024/05/16 07:24

在上一篇的基础上实现下拉刷新功能。主要通过对滚动状态和手势监听实现这一功能,下面我们看一下代码:

1.header.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <RelativeLayout  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:paddingBottom="10dip"  
  11.         android:paddingTop="10dip" >  
  12.   
  13.         <LinearLayout  
  14.             android:id="@+id/layout"  
  15.             android:layout_width="wrap_content"  
  16.             android:layout_height="wrap_content"  
  17.             android:layout_centerInParent="true"  
  18.             android:gravity="center"  
  19.             android:orientation="vertical" >  
  20.   
  21.             <TextView  
  22.                 android:id="@+id/tip"  
  23.                 android:layout_width="wrap_content"  
  24.                 android:layout_height="wrap_content"  
  25.                 android:text="下拉可以刷新!" />  
  26.   
  27.             <TextView  
  28.                 android:id="@+id/lastupdate_time"  
  29.                 android:layout_width="wrap_content"  
  30.                 android:layout_height="wrap_content" />  
  31.         </LinearLayout>  
  32.   
  33.         <ImageView  
  34.             android:id="@+id/arrow"  
  35.             android:layout_width="wrap_content"  
  36.             android:layout_height="wrap_content"  
  37.             android:layout_toLeftOf="@id/layout"  
  38.             android:layout_marginRight="20dip"  
  39.             android:src="@drawable/pull_to_refresh_arrow" />  
  40.   
  41.         <ProgressBar  
  42.             android:id="@+id/progress"  
  43.             style="?android:attr/progressBarStyleSmall"  
  44.             android:layout_width="wrap_content"  
  45.             android:layout_height="wrap_content"  
  46.             android:layout_toLeftOf="@id/layout"  
  47.             android:layout_marginRight="20dip"  
  48.             android:visibility="gone" />  
  49.     </RelativeLayout>  
  50.   
  51. </LinearLayout>  

2.LoadListView.java:

[java] view plaincopy
  1. package com.example.listviewscrolldemo;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5.   
  6. import android.content.Context;  
  7. import android.util.AttributeSet;  
  8. import android.util.Log;  
  9. import android.view.LayoutInflater;  
  10. import android.view.MotionEvent;  
  11. import android.view.View;  
  12. import android.view.ViewGroup;  
  13. import android.view.animation.RotateAnimation;  
  14. import android.widget.AbsListView;  
  15. import android.widget.AbsListView.OnScrollListener;  
  16. import android.widget.ImageView;  
  17. import android.widget.ListView;  
  18. import android.widget.ProgressBar;  
  19. import android.widget.TextView;  
  20.   
  21. public class LoadListView extends ListView implements OnScrollListener {  
  22.     private int lastVisibleItem;// 最后一个可见项  
  23.     private int totalItems;// 所有项  
  24.     private int firstVisibleItem;// 第一可见项  
  25.     private View footer, header;// 底部布局  
  26.     private Boolean isLoading = false;  
  27.     private Boolean isRemark = false;// 判断在当前页面的最顶端并下滑;  
  28.     private int startY;// Y坐标值  
  29.     private ILoadListener iListener;  
  30.     private RLoadListener rListener;  
  31.     private int scrollState;// 当前滚动状态;全局变量  
  32.     private int headerHeight;// 顶部布局文件的高度;  
  33.   
  34.     final int NONE = 0;// 正常状态;  
  35.     final int PULL = 1;// 提示下拉状态;  
  36.     final int RELESE = 2;// 提示释放状态;  
  37.     final int REFLASHING = 3;// 刷新状态;  
  38.   
  39.     private int state;// 判断当前状态  
  40.   
  41.     public LoadListView(Context context) {  
  42.         super(context);  
  43.         initView(context);  
  44.     }  
  45.   
  46.     public LoadListView(Context context, AttributeSet attrs) {  
  47.         super(context, attrs);  
  48.         initView(context);  
  49.     }  
  50.   
  51.     public LoadListView(Context context, AttributeSet attrs, int defStyleAttr) {  
  52.         super(context, attrs, defStyleAttr);  
  53.         initView(context);  
  54.     }  
  55.   
  56.     /** 
  57.      * 添加底部加载提示到布局Listview 
  58.      *  
  59.      * @param context 
  60.      */  
  61.     private void initView(Context context) {  
  62.         LayoutInflater inflater = LayoutInflater.from(context);  
  63.         footer = inflater.inflate(R.layout.footer, null);  
  64.         header = inflater.inflate(R.layout.header_layout, null);  
  65.         footer.findViewById(R.id.ll_footer).setVisibility(View.GONE);// 首先设置加载提示不可见  
  66.         measureView(header);  
  67.         headerHeight = header.getMeasuredHeight();  
  68.         Log.i("tag""headerHeight = " + headerHeight);  
  69.         topPadding(-headerHeight);  
  70.         this.addFooterView(footer);  
  71.         this.addHeaderView(header);  
  72.         this.setOnScrollListener(this);// 设置滚动监听  
  73.   
  74.     }  
  75.   
  76.     /** 
  77.      * 通知父布局,占用的宽,高; 
  78.      *  
  79.      * @param view 
  80.      */  
  81.     private void measureView(View view) {  
  82.         ViewGroup.LayoutParams p = view.getLayoutParams();  
  83.         if (p == null) {  
  84.             p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);  
  85.         }  
  86.         int width = ViewGroup.getChildMeasureSpec(00, p.width);  
  87.         int height;  
  88.         int tempHeight = p.height;  
  89.         if (tempHeight > 0) {  
  90.             height = MeasureSpec.makeMeasureSpec(tempHeight, MeasureSpec.EXACTLY);  
  91.         } else {  
  92.             height = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);  
  93.         }  
  94.         view.measure(width, height);  
  95.     }  
  96.   
  97.     /** 
  98.      * 设置header 布局 上边距; 
  99.      *  
  100.      * @param topPadding 
  101.      */  
  102.     private void topPadding(int topPadding) {  
  103.         header.setPadding(header.getPaddingLeft(), topPadding, header.getPaddingRight(), header.getPaddingBottom());  
  104.         header.invalidate();  
  105.     }  
  106.   
  107.     @Override  
  108.     public void onScrollStateChanged(AbsListView view, int scrollState) {  
  109.         this.scrollState = scrollState;  
  110.         if (lastVisibleItem == totalItems && scrollState == SCROLL_STATE_IDLE) {  
  111.   
  112.             if (!isLoading) {// 判断不是正在加载!  
  113.                 footer.findViewById(R.id.ll_footer).setVisibility(View.VISIBLE);// 首先设置加载提示可见  
  114.                 iListener.onLoad();  
  115.                 isLoading = true;  
  116.             }  
  117.   
  118.         }  
  119.   
  120.     }  
  121.   
  122.     @Override  
  123.     public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {  
  124.         this.lastVisibleItem = firstVisibleItem + visibleItemCount;  
  125.         this.totalItems = totalItemCount;  
  126.         this.firstVisibleItem = firstVisibleItem;  
  127.     }  
  128.   
  129.     // 传递  
  130.     public void setInterface(ILoadListener iListener) {  
  131.         this.iListener = iListener;  
  132.     }  
  133.   
  134.     public void setRefreshInterface(RLoadListener rListener) {  
  135.         this.rListener = rListener;  
  136.     }  
  137.   
  138.     /** 
  139.      * 加载更多数据的回调接口 
  140.      *  
  141.      * @author Administrator 
  142.      * 
  143.      */  
  144.     public interface ILoadListener {  
  145.         public void onLoad();  
  146.     }  
  147.   
  148.     /** 
  149.      * 下拉刷新回调接口 
  150.      *  
  151.      * @author Administrator 
  152.      * 
  153.      */  
  154.     public interface RLoadListener {  
  155.         public void onRefresh();  
  156.     }  
  157.   
  158.     // 加载完毕  
  159.     public void loadCompleted() {  
  160.         isLoading = false;  
  161.         footer.findViewById(R.id.ll_footer).setVisibility(View.GONE);  
  162.     }  
  163.   
  164.     @Override  
  165.     public boolean onTouchEvent(MotionEvent ev) {  
  166.         // TODO Auto-generated method stub  
  167.         switch (ev.getAction()) {  
  168.         case MotionEvent.ACTION_DOWN://下拉  
  169.             if (firstVisibleItem == 0) {  
  170.                 isRemark = true;  
  171.                 startY = (int) ev.getY();  
  172.             }  
  173.             break;  
  174.   
  175.         case MotionEvent.ACTION_MOVE://移动  
  176.             onMove(ev);  
  177.             break;  
  178.         case MotionEvent.ACTION_UP://上拉  
  179.             if (state == RELESE) {  
  180.                 state = REFLASHING;  
  181.                 // 加载最新数据;  
  182.                 reflashViewByState();  
  183.                 rListener.onRefresh();  
  184.             } else if (state == PULL) {  
  185.                 state = NONE;  
  186.                 isRemark = false;  
  187.                 reflashViewByState();  
  188.             }  
  189.             break;  
  190.         }  
  191.         return super.onTouchEvent(ev);  
  192.     }  
  193.   
  194.     /** 
  195.      * 判断移动过程操作; 
  196.      *  
  197.      * @param ev 
  198.      */  
  199.     private void onMove(MotionEvent ev) {  
  200.         if (!isRemark) {  
  201.             return;  
  202.         }  
  203.         int tempY = (int) ev.getY();  
  204.         int space = tempY - startY;  
  205.         int topPadding = space - headerHeight;  
  206.         switch (state) {  
  207.         case NONE:  
  208.             if (space > 0) {// 向下滑动  
  209.                 state = PULL;  
  210.                 reflashViewByState();  
  211.             }  
  212.             break;  
  213.         case PULL:  
  214.             topPadding(topPadding);  
  215.             if (space > headerHeight + 30 && scrollState == SCROLL_STATE_TOUCH_SCROLL) {// 如果正在滚动切超过30  
  216.                 state = RELESE;  
  217.                 reflashViewByState();  
  218.             }  
  219.             break;  
  220.         case RELESE:  
  221.             topPadding(topPadding);  
  222.             if (space < headerHeight + 30) {  
  223.                 state = PULL;  
  224.                 reflashViewByState();  
  225.             } else if (space <= 0) {  
  226.                 state = NONE;  
  227.                 isRemark = false;  
  228.                 reflashViewByState();  
  229.             }  
  230.             break;  
  231.         }  
  232.     }  
  233.   
  234.     /** 
  235.      * 根据当前状态,改变界面显示; 
  236.      */  
  237.     private void reflashViewByState() {  
  238.         TextView tip = (TextView) header.findViewById(R.id.tip);  
  239.         ImageView arrow = (ImageView) header.findViewById(R.id.arrow);  
  240.         ProgressBar progress = (ProgressBar) header.findViewById(R.id.progress);  
  241.         RotateAnimation anim = new RotateAnimation(0180, RotateAnimation.RELATIVE_TO_SELF, 0.5f,  
  242.                 RotateAnimation.RELATIVE_TO_SELF, 0.5f);  
  243.         anim.setDuration(500);  
  244.         anim.setFillAfter(true);  
  245.         RotateAnimation anim1 = new RotateAnimation(1800, RotateAnimation.RELATIVE_TO_SELF, 0.5f,  
  246.                 RotateAnimation.RELATIVE_TO_SELF, 0.5f);  
  247.         anim1.setDuration(500);  
  248.         anim1.setFillAfter(true);  
  249.         /** 
  250.          * 四种状态 
  251.          */  
  252.         switch (state) {  
  253.         case NONE:  
  254.             arrow.clearAnimation();  
  255.             topPadding(-headerHeight);  
  256.             break;  
  257.   
  258.         case PULL:  
  259.             arrow.setVisibility(View.VISIBLE);  
  260.             progress.setVisibility(View.GONE);  
  261.             tip.setText("下拉可以刷新!");  
  262.             arrow.clearAnimation();  
  263.             arrow.setAnimation(anim1);  
  264.             break;  
  265.         case RELESE:  
  266.             arrow.setVisibility(View.VISIBLE);  
  267.             progress.setVisibility(View.GONE);  
  268.             tip.setText("松开可以刷新!");  
  269.             arrow.clearAnimation();  
  270.             arrow.setAnimation(anim);  
  271.             break;  
  272.         case REFLASHING:  
  273.             topPadding(50);  
  274.             arrow.setVisibility(View.GONE);  
  275.             progress.setVisibility(View.VISIBLE);  
  276.             tip.setText("正在刷新...");  
  277.             arrow.clearAnimation();  
  278.             break;  
  279.         }  
  280.     }  
  281.   
  282.     /** 
  283.      * 获取完数据; 
  284.      */  
  285.     public void reflashComplete() {  
  286.         state = NONE;  
  287.         isRemark = false;  
  288.         reflashViewByState();  
  289.         TextView lastupdatetime = (TextView) header.findViewById(R.id.lastupdate_time);  
  290.         SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");  
  291.         Date date = new Date(System.currentTimeMillis());  
  292.         String time = format.format(date);  
  293.         lastupdatetime.setText(time);  
  294.     }  
  295. }  

这里我们定义了四种状态:

        final int NONE = 0;// 正常状态;
final int PULL = 1;// 提示下拉状态;(下拉距离比较短,此时松开不刷新)
final int RELESE = 2;// 提示释放状态;(下拉距离较长,此时松开刷新)
final int REFLASHING = 3;// 刷新状态;(松开状态,正在刷新)

       这四种状态决定了header布局的不同展示效果,具体由reflashViewByState()方法实现。

       onMove()方法通过判断移动过程,实现四种状态之间的转换。

[java] view plaincopy
  1. package com.example.listviewscrolldemo;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import com.example.listviewscrolldemo.LoadListView.ILoadListener;  
  7. import com.example.listviewscrolldemo.LoadListView.RLoadListener;  
  8.   
  9. import android.app.Activity;  
  10. import android.os.Bundle;  
  11. import android.os.Handler;  
  12. import android.widget.ArrayAdapter;  
  13.   
  14. public class MainActivity extends Activity implements ILoadListener, RLoadListener {  
  15.     private LoadListView mListView;  
  16.     private ArrayAdapter<String> adapter;  
  17.     private List<String> datas;  
  18.   
  19.     @Override  
  20.     protected void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.activity_main);  
  23.         initViews();  
  24.         initDatas();  
  25.     }  
  26.   
  27.     private void initDatas() {  
  28.         for (int i = 1; i < 21; i++) {  
  29.             datas.add("数据" + i + "");  
  30.         }  
  31.   
  32.     }  
  33.   
  34.     private void initMoreDatas() {  
  35.         for (int i = 1; i < 3; i++) {  
  36.             datas.add("新数据" + i + "");  
  37.         }  
  38.   
  39.     }  
  40.   
  41.     private void initViews() {  
  42.         mListView = (LoadListView) findViewById(R.id.lv_main);  
  43.         mListView.setInterface(this);  
  44.         mListView.setRefreshInterface(this);  
  45.         datas = new ArrayList<String>();  
  46.         adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, datas);  
  47.         // adapter=new  
  48.         // ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1);  
  49.         mListView.setAdapter(adapter);  
  50.     }  
  51.   
  52.     @Override  
  53.     public void onLoad() {  
  54.         // 添加延时效果  
  55.         Handler handler = new Handler();  
  56.         handler.postDelayed(new Runnable() {  
  57.             public void run() {  
  58.   
  59.                 initMoreDatas();// 获取更多数据  
  60.                 adapter.notifyDataSetChanged();// 刷新ListView  
  61.                 mListView.loadCompleted();// 隐藏加载提示  
  62.             }  
  63.         }, 2000);  
  64.   
  65.     }  
  66.   
  67.     @Override  
  68.     public void onRefresh() {  
  69.         // 添加延时效果  
  70.         Handler handler = new Handler();  
  71.         handler.postDelayed(new Runnable() {  
  72.             public void run() {  
  73.   
  74.                 initRefreshDatas();// 获取更多数据  
  75.                 adapter.notifyDataSetChanged();// 刷新ListView  
  76.                 mListView.reflashComplete();// 隐藏刷新提示  
  77.             }  
  78.   
  79.         }, 2000);  
  80.     }  
  81.   
  82.     private void initRefreshDatas() {  
  83.         // datas.add("新数据" + i + "");  
  84.         datas.add(0"下拉刷新数据" + 1 + "");//此方法插入表头  
  85.         datas.add(0"下拉刷新数据" + 2 + "");  
  86.     }  
  87.   
  88. }  

运行本实例如下:



源码下载


0 0