ListView下拉回弹刷新

来源:互联网 发布:数据分析服务合同 编辑:程序博客网 时间:2024/06/11 20:25

现在QQ空间和新浪微博ListView下拉刷新做的比较炫,正好公司也有这样的需求,实现起来还是相对简单的。关键是要自定义一个ListView头部(初始化的时候里面的控件是不可见的),然后在点击、拖动、松开的时候触发事件,显示ListView头,计算出拖拽的距离,跟ListView头的高度做比较,以此来显示对应的ListView头里的控件(下拉图标、提示文字、圆形进度条等)。好了,下面贴出效果图:



好,开始上代码,先是布局文件main.xml,没什么好说的:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical"  
  6.     android:background="@color/mainColor" >  
  7.       
  8.     <!-- 这里是自定义的ListView -->  
  9.     <com.focustech.android.CustomListView  
  10.         android:id="@+id/list"  
  11.         android:layout_width="fill_parent"  
  12.         android:layout_height="wrap_content"  
  13.     />  
  14.   
  15. </LinearLayout>  

ListView头布局head.xml:

  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="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <RelativeLayout  
  8.         android:id="@+id/head_contentLayout"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:paddingLeft="30dp" >  
  12.   
  13.         <FrameLayout  
  14.             android:layout_width="wrap_content"  
  15.             android:layout_height="wrap_content"  
  16.             android:layout_alignParentLeft="true"  
  17.             android:layout_centerVertical="true" >  
  18.   
  19.             <ImageView  
  20.                 android:id="@+id/head_arrowImageView"  
  21.                 android:layout_width="wrap_content"  
  22.                 android:layout_height="wrap_content"  
  23.                 android:layout_gravity="center"  
  24.                 android:src="@drawable/ic_pulltorefresh_arrow" />  
  25.   
  26.             <ProgressBar  
  27.                 android:id="@+id/head_progressBar"  
  28.                 style="?android:attr/progressBarStyleSmall"  
  29.                 android:layout_width="wrap_content"  
  30.                 android:layout_height="wrap_content"  
  31.                 android:layout_gravity="center"  
  32.                 android:visibility="gone" />  
  33.         </FrameLayout>  
  34.   
  35.         <LinearLayout  
  36.             android:layout_width="wrap_content"  
  37.             android:layout_height="wrap_content"  
  38.             android:layout_centerHorizontal="true"  
  39.             android:gravity="center_horizontal"  
  40.             android:orientation="vertical" >  
  41.   
  42.             <TextView  
  43.                 android:id="@+id/head_tipsTextView"  
  44.                 android:layout_width="wrap_content"  
  45.                 android:layout_height="wrap_content"  
  46.                 android:text="下拉可以刷新"  
  47.                 android:textColor="#ffffff"  
  48.                 android:textSize="20sp" />  
  49.   
  50.             <TextView  
  51.                 android:id="@+id/head_lastUpdatedTextView"  
  52.                 android:layout_width="wrap_content"  
  53.                 android:layout_height="wrap_content"  
  54.                 android:text="最近更新"  
  55.                 android:textColor="#cc6600"  
  56.                 android:textSize="10sp" />  
  57.               
  58.         </LinearLayout>  
  59.     </RelativeLayout>  
  60.   
  61.   
  62. </LinearLayout>  

ListView item项布局listview_item.xml:

  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="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.      <ImageView  
  8.         android:id="@+id/imageView"  
  9.          android:layout_width="wrap_content"  
  10.        android:layout_height="wrap_content"  
  11.          android:src="@drawable/pretty_girl"  
  12.     />  
  13.      <TextView  
  14.         android:id="@+id/textview"  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content"  
  17.     />  
  18.   
  19. </LinearLayout>  

清单文件也贴出来吧,其实就是自动生成的,什么都不用改:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.focustech.android"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk android:minSdkVersion="14" />  
  8.   
  9.     <application  
  10.         android:icon="@drawable/ic_launcher"  
  11.         android:label="@string/app_name" >  
  12.         <activity  
  13.             android:label="@string/app_name"  
  14.             android:name="com.focustech.android.MainActivity" >  
  15.             <intent-filter >  
  16.                 <action android:name="android.intent.action.MAIN" />  
  17.   
  18.                 <category android:name="android.intent.category.LAUNCHER" />  
  19.             </intent-filter>  
  20.         </activity>  
  21.     </application>  
  22.   
  23. </manifest>  

此Demo的Activity:

  1. package com.focustech.android;  
  2.   
  3. import android.app.Activity;  
  4. import android.database.DataSetObserver;  
  5. import android.graphics.Color;  
  6. import android.os.Bundle;  
  7. import android.view.LayoutInflater;  
  8. import android.view.View;  
  9. import android.view.ViewGroup;  
  10. import android.widget.ListAdapter;  
  11. import android.widget.TextView;  
  12.   
  13. import com.focustech.android.CustomListView.OnRefreshListener;  
  14. import com.focustech.android.R;  
  15.   
  16. public class MainActivity extends Activity {  
  17.   
  18.     private ListAdapter adapter;  
  19.     int size = 10;  
  20.   
  21.     public void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.main);  
  24.   
  25.         final CustomListView list = (CustomListView) findViewById(R.id.list);  
  26.   
  27.         adapter = new ListAdapter() {  
  28.             public void unregisterDataSetObserver(DataSetObserver arg0) {  
  29.   
  30.             }  
  31.   
  32.             public void registerDataSetObserver(DataSetObserver arg0) {  
  33.   
  34.             }  
  35.   
  36.             public boolean isEmpty() {  
  37.                 return false;  
  38.             }  
  39.   
  40.             public boolean hasStableIds() {  
  41.                 return false;  
  42.             }  
  43.   
  44.             public int getViewTypeCount() {  
  45.                 return 1;  
  46.             }  
  47.   
  48.             public View getView(int position, View convertView, ViewGroup parent) {  
  49.                 convertView = LayoutInflater.from(getApplicationContext())  
  50.                         .inflate(R.layout.listview_item, null);  
  51.   
  52.                 TextView mTextView = (TextView) convertView  
  53.                         .findViewById(R.id.textview);  
  54.                 mTextView.setText("pretty girl" + position);  
  55.                 mTextView.setTextColor(Color.RED);  
  56.                 return convertView;  
  57.             }  
  58.   
  59.             public int getItemViewType(int arg0) {  
  60.                 return arg0;  
  61.             }  
  62.   
  63.             public long getItemId(int arg0) {  
  64.                 return arg0;  
  65.             }  
  66.   
  67.             public Object getItem(int arg0) {  
  68.                 return null;  
  69.             }  
  70.   
  71.             public int getCount() {  
  72.                 return size;  
  73.             }  
  74.   
  75.             @Override  
  76.             public boolean isEnabled(int position) {  
  77.                 return false;  
  78.             }  
  79.   
  80.             @Override  
  81.             public boolean areAllItemsEnabled() {  
  82.                 return false;  
  83.             }  
  84.         };  
  85.   
  86.         list.setAdapter(adapter);  
  87.         // 在list上注册自定义的监听器   
  88.         list.setonRefreshListener(new OnRefreshListener() {  
  89.             public void onRefresh() {  
  90.                 new Thread(new Runnable() {  
  91.                     public void run() {  
  92.                         try {  
  93.                             Thread.sleep(1000);  
  94.                         } catch (Exception e) {  
  95.                         }  
  96.   
  97.                         runOnUiThread(new Runnable() {  
  98.                             public void run() {  
  99.                                 list.onRefreshComplete();  
  100.                             }  
  101.                         });  
  102.                         size++;  
  103.   
  104.                     }  
  105.                 }).start();  
  106.             }  
  107.         });  
  108.     }  
  109.   
  110. }  

实现了OnScrollListener的自定义ListView:

  1. package com.focustech.Android;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import android.content.Context;  
  6. import android.util.AttributeSet;  
  7. import android.util.Log;  
  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.AbsListView.OnScrollListener;  
  16. import android.widget.ImageView;  
  17. import android.widget.LinearLayout;  
  18. import android.widget.ListView;  
  19. import android.widget.ProgressBar;  
  20. import android.widget.TextView;  
  21.   
  22. import com.focustech.android.R;  
  23.   
  24. public class CustomListView extends ListView implements OnScrollListener {  
  25.   
  26.     // 松开刷新标志   
  27.     private final static int RELEASE_To_REFRESH = 0;  
  28.     // 下拉刷新标志   
  29.     private final static int PULL_To_REFRESH = 1;  
  30.     // 正在刷新标志   
  31.     private final static int REFRESHING = 2;  
  32.     // 刷新完成标志   
  33.     private final static int DONE = 3;  
  34.   
  35.     private LayoutInflater inflater;  
  36.   
  37.     private LinearLayout headView;  
  38.     private TextView tipsTextview;  
  39.     private TextView lastUpdatedTextView;  
  40.     private ImageView arrowImageView;  
  41.     private ProgressBar progressBar;  
  42.     // 用来设置箭头图标动画效果   
  43.     private RotateAnimation animation;  
  44.     private RotateAnimation reverseAnimation;  
  45.   
  46.     // 用于保证startY的值在一个完整的touch事件中只被记录一次   
  47.     private boolean isRecored;  
  48.   
  49.     private int headContentWidth;  
  50.     private int headContentHeight;  
  51.   
  52.     private int startY;  
  53.     private int firstItemIndex;  
  54.   
  55.     private int state;  
  56.   
  57.     private boolean isBack;  
  58.   
  59.     public OnRefreshListener refreshListener;  
  60.   
  61.     private final static String TAG = "Monitor Current Infomation";  
  62.   
  63.     public CustomListView(Context context, AttributeSet attrs) {  
  64.         super(context, attrs);  
  65.         init(context);  
  66.     }  
  67.   
  68.     private void init(Context context) {  
  69.   
  70.         inflater = LayoutInflater.from(context);  
  71.         headView = (LinearLayout) inflater.inflate(R.layout.head, null);  
  72.   
  73.         arrowImageView = (ImageView) headView  
  74.                 .findViewById(R.id.head_arrowImageView);  
  75.         arrowImageView.setMinimumWidth(50);  
  76.         arrowImageView.setMinimumHeight(50);  
  77.         progressBar = (ProgressBar) headView  
  78.                 .findViewById(R.id.head_progressBar);  
  79.         tipsTextview = (TextView) headView.findViewById(R.id.head_tipsTextView);  
  80.         lastUpdatedTextView = (TextView) headView  
  81.                 .findViewById(R.id.head_lastUpdatedTextView);  
  82.   
  83.         measureView(headView);  
  84.   
  85.         headContentHeight = headView.getMeasuredHeight();  
  86.         headContentWidth = headView.getMeasuredWidth();  
  87.   
  88.         headView.setPadding(0, -1 * headContentHeight, 00);  
  89.         headView.invalidate();  
  90.   
  91.         Log.v("size""width:" + headContentWidth + " height:"  
  92.                 + headContentHeight);  
  93.   
  94.         addHeaderView(headView);  
  95.         setOnScrollListener(this);  
  96.   
  97.         animation = new RotateAnimation(0, -180,  
  98.                 RotateAnimation.RELATIVE_TO_SELF, 0.5f,  
  99.                 RotateAnimation.RELATIVE_TO_SELF, 0.5f);  
  100.         animation.setInterpolator(new LinearInterpolator());  
  101.         animation.setDuration(500);  
  102.         animation.setFillAfter(true);  
  103.   
  104.         reverseAnimation = new RotateAnimation(-1800,  
  105.                 RotateAnimation.RELATIVE_TO_SELF, 0.5f,  
  106.                 RotateAnimation.RELATIVE_TO_SELF, 0.5f);  
  107.         reverseAnimation.setInterpolator(new LinearInterpolator());  
  108.         reverseAnimation.setDuration(500);  
  109.         reverseAnimation.setFillAfter(true);  
  110.     }  
  111.   
  112.     public void onScroll(AbsListView arg0, int firstVisiableItem, int arg2,  
  113.             int arg3) {  
  114.         firstItemIndex = firstVisiableItem;  
  115.     }  
  116.   
  117.     public void onScrollStateChanged(AbsListView arg0, int arg1) {  
  118.     }  
  119.   
  120.     public boolean onTouchEvent(MotionEvent event) {  
  121.         switch (event.getAction()) {  
  122.         case MotionEvent.ACTION_DOWN:  
  123.             if (firstItemIndex == 0 && !isRecored) {  
  124.                 startY = (int) event.getY();  
  125.                 isRecored = true;  
  126.   
  127.                 Log.v(TAG, "记录按下时的位置");  
  128.             }  
  129.             break;  
  130.   
  131.         case MotionEvent.ACTION_UP:  
  132.   
  133.             if (state != REFRESHING) {  
  134.                 if (state == DONE) {  
  135.                     Log.v(TAG, "什么都不做");  
  136.                 }  
  137.                 if (state == PULL_To_REFRESH) {  
  138.                     state = DONE;  
  139.                     changeHeaderViewByState();  
  140.   
  141.                     Log.v(TAG, "由下拉刷新状态到刷新完成状态");  
  142.                 }  
  143.                 if (state == RELEASE_To_REFRESH) {  
  144.                     state = REFRESHING;  
  145.                     changeHeaderViewByState();  
  146.                     onRefresh();  
  147.   
  148.                     Log.v(TAG, "由松开刷新状态,到刷新完成状态");  
  149.                 }  
  150.             }  
  151.   
  152.             isRecored = false;  
  153.             isBack = false;  
  154.   
  155.             break;  
  156.   
  157.         case MotionEvent.ACTION_MOVE:  
  158.             int tempY = (int) event.getY();  
  159.             if (!isRecored && firstItemIndex == 0) {  
  160.                 Log.v(TAG, "记录拖拽时的位置");  
  161.                 isRecored = true;  
  162.                 startY = tempY;  
  163.             }  
  164.             if (state != REFRESHING && isRecored) {  
  165.                 // 可以松开刷新了   
  166.                 if (state == RELEASE_To_REFRESH) {  
  167.                     // 往上推,推到屏幕足够掩盖head的程度,但还没有全部掩盖   
  168.                     if ((tempY - startY < headContentHeight)  
  169.                             && (tempY - startY) > 0) {  
  170.                         state = PULL_To_REFRESH;  
  171.                         changeHeaderViewByState();  
  172.   
  173.                         Log.v(TAG, "由松开刷新状态转变到下拉刷新状态");  
  174.                     }  
  175.                     // 一下子推到顶   
  176.                     else if (tempY - startY <= 0) {  
  177.                         state = DONE;  
  178.                         changeHeaderViewByState();  
  179.   
  180.                         Log.v(TAG, "由松开刷新状态转变到done状态");  
  181.                     }  
  182.                     // 往下拉,或者还没有上推到屏幕顶部掩盖head   
  183.                     else {  
  184.                         // 不用进行特别的操作,只用更新paddingTop的值就行了   
  185.                     }  
  186.                 }  
  187.                 // 还没有到达显示松开刷新的时候,DONE或者是PULL_To_REFRESH状态   
  188.                 if (state == PULL_To_REFRESH) {  
  189.                     // 下拉到可以进入RELEASE_TO_REFRESH的状态   
  190.                     if (tempY - startY >= headContentHeight) {  
  191.                         state = RELEASE_To_REFRESH;  
  192.                         isBack = true;  
  193.                         changeHeaderViewByState();  
  194.   
  195.                         Log.v(TAG, "由done或者下拉刷新状态转变到松开刷新");  
  196.                     }  
  197.                     // 上推到顶了   
  198.                     else if (tempY - startY <= 0) {  
  199.                         state = DONE;  
  200.                         changeHeaderViewByState();  
  201.   
  202.                         Log.v(TAG, "由Done或者下拉刷新状态转变到done状态");  
  203.                     }  
  204.                 }  
  205.   
  206.                 // done状态下   
  207.                 if (state == DONE) {  
  208.                     if (tempY - startY > 0) {  
  209.                         state = PULL_To_REFRESH;  
  210.                         changeHeaderViewByState();  
  211.                     }  
  212.                 }  
  213.   
  214.                 // 更新headView的size   
  215.                 if (state == PULL_To_REFRESH) {  
  216.                     headView.setPadding(0, -1 * headContentHeight  
  217.                             + (tempY - startY), 00);  
  218.                     headView.invalidate();  
  219.                 }  
  220.   
  221.                 // 更新headView的paddingTop   
  222.                 if (state == RELEASE_To_REFRESH) {  
  223.                     headView.setPadding(0, tempY - startY - headContentHeight,  
  224.                             00);  
  225.                     headView.invalidate();  
  226.                 }  
  227.             }  
  228.             break;  
  229.         }  
  230.         return super.onTouchEvent(event);  
  231.     }  
  232.   
  233.     // 当状态改变时候,调用该方法,以更新界面   
  234.     private void changeHeaderViewByState() {  
  235.         switch (state) {  
  236.         case RELEASE_To_REFRESH:  
  237.   
  238.             arrowImageView.setVisibility(View.VISIBLE);  
  239.             progressBar.setVisibility(View.GONE);  
  240.             tipsTextview.setVisibility(View.VISIBLE);  
  241.             lastUpdatedTextView.setVisibility(View.VISIBLE);  
  242.   
  243.             arrowImageView.clearAnimation();  
  244.             arrowImageView.startAnimation(animation);  
  245.   
  246.             tipsTextview.setText("松开可以刷新");  
  247.   
  248.             Log.v(TAG, "当前状态,松开刷新");  
  249.             break;  
  250.         case PULL_To_REFRESH:  
  251.   
  252.             progressBar.setVisibility(View.GONE);  
  253.             tipsTextview.setVisibility(View.VISIBLE);  
  254.             lastUpdatedTextView.setVisibility(View.VISIBLE);  
  255.             arrowImageView.clearAnimation();  
  256.             arrowImageView.setVisibility(View.VISIBLE);  
  257.             if (isBack) {  
  258.                 isBack = false;  
  259.                 arrowImageView.clearAnimation();  
  260.                 arrowImageView.startAnimation(reverseAnimation);  
  261.   
  262.                 tipsTextview.setText("下拉可以刷新");  
  263.             } else {  
  264.                 tipsTextview.setText("下拉可以刷新");  
  265.             }  
  266.             Log.v(TAG, "当前状态,下拉刷新");  
  267.             break;  
  268.   
  269.         case REFRESHING:  
  270.   
  271.             headView.setPadding(0000);  
  272.             headView.invalidate();  
  273.   
  274.             progressBar.setVisibility(View.VISIBLE);  
  275.             arrowImageView.clearAnimation();  
  276.             arrowImageView.setVisibility(View.GONE);  
  277.             tipsTextview.setText("正在刷新,请稍后...");  
  278.             lastUpdatedTextView.setVisibility(View.GONE);  
  279.   
  280.             Log.v(TAG, "当前状态,正在刷新...");  
  281.             break;  
  282.         case DONE:  
  283.             headView.setPadding(0, -1 * headContentHeight, 00);  
  284.             headView.invalidate();  
  285.   
  286.             progressBar.setVisibility(View.GONE);  
  287.             arrowImageView.clearAnimation();  
  288.             // 此处更换图标   
  289.             arrowImageView.setImageResource(R.drawable.ic_pulltorefresh_arrow);  
  290.   
  291.             tipsTextview.setText("下拉可以刷新");  
  292.             lastUpdatedTextView.setVisibility(View.VISIBLE);  
  293.   
  294.             Log.v(TAG, "当前状态,done");  
  295.             break;  
  296.         }  
  297.     }  
  298.   
  299.     public void setonRefreshListener(OnRefreshListener refreshListener) {  
  300.         this.refreshListener = refreshListener;  
  301.     }  
  302.   
  303.     public interface OnRefreshListener {  
  304.         public void onRefresh();  
  305.     }  
  306.   
  307.     public void onRefreshComplete() {  
  308.         state = DONE;  
  309.         lastUpdatedTextView.setText("最近更新:" + new Date().toLocaleString());  
  310.         changeHeaderViewByState();  
  311.     }  
  312.   
  313.     private void onRefresh() {  
  314.         if (refreshListener != null) {  
  315.             refreshListener.onRefresh();  
  316.         }  
  317.     }  
  318.   
  319.     // 此处是“估计”headView的width以及height   
  320.     private void measureView(View child) {  
  321.         ViewGroup.LayoutParams p = child.getLayoutParams();  
  322.         if (p == null) {  
  323.             p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,  
  324.                     ViewGroup.LayoutParams.WRAP_CONTENT);  
  325.         }  
  326.         int childWidthSpec = ViewGroup.getChildMeasureSpec(00 + 0, p.width);  
  327.         int lpHeight = p.height;  
  328.         int childHeightSpec;  
  329.         if (lpHeight > 0) {  
  330.             childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,  
  331.                     MeasureSpec.EXACTLY);  
  332.         } else {  
  333.             childHeightSpec = MeasureSpec.makeMeasureSpec(0,  
  334.                     MeasureSpec.UNSPECIFIED);  
  335.         }  
  336.         child.measure(childWidthSpec, childHeightSpec);  
  337.     }  
  338.   
  339. }  

原创粉丝点击