欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ScrollView下拉刷新 博客分类: android  

程序员文章站 2024-03-11 12:47:13
...
package com.example.refreshscrollview;

import java.util.Date;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

public class RefreshScrollView extends ScrollView {
	private final static int RATIO = 3;

	/**
	 * ScrollView里面的布局
	 */
	private LinearLayout innerLayout;

	private LinearLayout refreshLayout;
	private ImageView ivArrow;
	private ProgressBar pbRefresh;
	private TextView tvPullDownTips;
	private TextView tvLastUpdate;

	private int headContentWidth;
	private int headContentHeight;

	private RotateAnimation animation; // 下拉动画
	private RotateAnimation reverseAnimation; // 反向动画

	private enum RefreshState {
		PULL_DOWN, RELEASE_TO_REFRESH, REFRESHING, DONE
	}; // 松手,下拉,正在刷新,刷新完成

	private RefreshState state;
	private boolean isBack; // 下拉到一定距离后,箭头是否转向
	private boolean isRecored; // 是否记录了滑动时的起始位置
	private int startY;

	private OnRefreshListener refreshListener = null;

	public RefreshScrollView(Context context) {
		super(context);
		init(context);
	}

	public RefreshScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	private void init(Context context) {
		LayoutInflater inflater = LayoutInflater.from(context);
		innerLayout = new LinearLayout(context);
		innerLayout.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT));
		innerLayout.setOrientation(LinearLayout.VERTICAL);

		refreshLayout = (LinearLayout) inflater.inflate(
				R.layout.refresh_widget_layout, null);
		ivArrow = (ImageView) refreshLayout.findViewById(R.id.iv_arrow);

		pbRefresh = (ProgressBar) refreshLayout.findViewById(R.id.pb_refresh);

		tvPullDownTips = (TextView) refreshLayout
				.findViewById(R.id.tv_pulldown_tips);
		tvLastUpdate = (TextView) refreshLayout
				.findViewById(R.id.tv_lastupdate);

		measureView(refreshLayout);

		headContentHeight = refreshLayout.getMeasuredHeight();
		headContentWidth = refreshLayout.getMeasuredWidth();
		refreshLayout.setPadding(0, -1 * headContentHeight, 0, 0);
		refreshLayout.invalidate();

		innerLayout.addView(refreshLayout);
		addView(innerLayout);

		animation = new RotateAnimation(0, -180,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		animation.setInterpolator(new LinearInterpolator());
		animation.setDuration(250);
		animation.setFillAfter(true);

		reverseAnimation = new RotateAnimation(-180, 0,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		reverseAnimation.setInterpolator(new LinearInterpolator());
		reverseAnimation.setDuration(200);
		reverseAnimation.setFillAfter(true);

		state = RefreshState.DONE;
		isRecored = false;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (refreshListener == null) {
			return super.onTouchEvent(event);
		}
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			if (getScrollY() == 0 && !isRecored) {
				isRecored = true;
				startY = (int) event.getY(); // 记录起始位置
			}
			break;
		case MotionEvent.ACTION_UP: // 移动一段距离后,如果是“下拉不完全”,那么改为“结束刷新”,如果是“下拉完全”,那么改为“正在刷新”,进入刷新
			if (state == RefreshState.PULL_DOWN) {
				state = RefreshState.DONE;
				changeHeaderViewByState();
			}
			if (state == RefreshState.RELEASE_TO_REFRESH) {
				state = RefreshState.REFRESHING;
				changeHeaderViewByState();
				onRefresh();
			}
			isRecored = false;
			isBack = false;

			break;
		case MotionEvent.ACTION_MOVE:
			int tempY = (int) event.getY(); // 移动过程中Y的坐标
			if (!isRecored && getScrollY() == 0) {
				isRecored = true;
				startY = tempY;
			}

			if (state == RefreshState.REFRESHING || !isRecored) {
				break;
			}
			// 滑动时状态为“下拉完全”,它可能滑动时进入“下拉不完全”或者向下滑动滚动条
			if (state == RefreshState.RELEASE_TO_REFRESH) {
				if (((tempY - startY) / RATIO < headContentHeight)
						&& (tempY - startY) > 0) {
					state = RefreshState.PULL_DOWN;
					changeHeaderViewByState();
				}
				if (tempY - startY <= 0) {
					state = RefreshState.DONE;
					changeHeaderViewByState();
				}
			}
			// "下拉不完成"状态可以转变成“下拉完全”或者滑动滚动条
			if (state == RefreshState.PULL_DOWN) {
				if ((tempY - startY) / RATIO >= headContentHeight) {
					state = RefreshState.RELEASE_TO_REFRESH;
					isBack = true;
					changeHeaderViewByState();
				} else if (tempY - startY <= 0) {
					state = RefreshState.DONE;
					changeHeaderViewByState();
				}
			}

			// 无下拉状态可以进入“下拉不完全状态” (滑动滚动条也是无下拉状态)
			if (state == RefreshState.DONE) {
				if (tempY - startY > 0) {
					state = RefreshState.PULL_DOWN;
					changeHeaderViewByState();
				}
			}

			// 下拉过程中,设置整个刷新控件的位置;在这两个下拉状态中,事件不会交给其它的view
			if (state == RefreshState.PULL_DOWN
					|| state == RefreshState.RELEASE_TO_REFRESH) {
				refreshLayout.setPadding(0, -1 * headContentHeight
						+ (tempY - startY) / RATIO, 0, 0);
				return true;
			}

			break;
		}

		return super.onTouchEvent(event);
	}

	private void changeHeaderViewByState() {
		switch (state) {
		case PULL_DOWN: // 下拉刷新,还没有拉到界限,这时候松手不会刷新
			pbRefresh.setVisibility(View.GONE);
			tvPullDownTips.setVisibility(View.VISIBLE);
			ivArrow.clearAnimation();
			ivArrow.setVisibility(View.VISIBLE);
			if (isBack) {
				isBack = false;
				ivArrow.clearAnimation();
				ivArrow.startAnimation(reverseAnimation);

				tvPullDownTips.setText("下拉刷新");
			} else {
				tvPullDownTips.setText("下拉刷新");
			}
			break;
		case RELEASE_TO_REFRESH: // 松手刷新,已经拉到界限,这时候松手会刷新
			ivArrow.setVisibility(View.VISIBLE);
			pbRefresh.setVisibility(View.GONE);
			tvPullDownTips.setVisibility(View.VISIBLE);
			tvLastUpdate.setVisibility(View.VISIBLE);
			ivArrow.clearAnimation();
			ivArrow.startAnimation(animation);
			tvPullDownTips.setText("松手刷新");
			break;
		case REFRESHING: // 正在刷新时,显示刷新进度圈,清除箭头
			refreshLayout.setPadding(0, 0, 0, 0);
			tvPullDownTips.setText("正在刷新...");
			pbRefresh.setVisibility(View.VISIBLE);
			ivArrow.clearAnimation();
			ivArrow.setVisibility(View.GONE);
			tvLastUpdate.setVisibility(View.VISIBLE);
			isRecored = false;
			break;
		case DONE: // 刷新完成,隐藏整个刷新控件,刷新进度圈消失
			refreshLayout.setPadding(0, -1 * headContentHeight, 0, 0); // 隐藏空间
			pbRefresh.setVisibility(View.GONE);
			ivArrow.clearAnimation();
			ivArrow.setImageResource(R.drawable.arrow);
			tvPullDownTips.setText("刷新完成");
			tvLastUpdate.setVisibility(View.VISIBLE);
			isRecored = false;
			break;
		default:
			break;
		}
	}

	private void measureView(View child) {
		ViewGroup.LayoutParams layoutParams = child.getLayoutParams();
		if (layoutParams == null) {
			layoutParams = new ViewGroup.LayoutParams(
					ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.MATCH_PARENT);
		}
		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0,
				layoutParams.width);
		int lpHeight = layoutParams.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
					MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0,
					MeasureSpec.UNSPECIFIED);
		}
		child.measure(childWidthSpec, childHeightSpec);
	}

	public void setonRefreshListener(OnRefreshListener refreshListener) {
		this.refreshListener = refreshListener;
	}

	public interface OnRefreshListener {
		public void onRefresh();
	}

	public void onRefreshComplete() {
		state = RefreshState.DONE;
		tvLastUpdate.setText("最新一次更新时间:" + new Date().toLocaleString());
		changeHeaderViewByState();
		invalidate();
		scrollTo(0, 0);
	}

	private void onRefresh() {
		if (refreshListener != null) {
			refreshListener.onRefresh();
		}
	}

	public void addChild(View child) {
		innerLayout.addView(child);
	}

	public void addChild(View child, int position) {
		innerLayout.addView(child, position);
	}
}

 

 

package com.example.refreshscrollview;

import java.util.Random;

import com.example.refreshscrollview.RefreshScrollView.OnRefreshListener;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
	private RefreshScrollView scrollView;
	private TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        scrollView = (RefreshScrollView)findViewById(R.id.scrollview1);
        View contentview=View.inflate(this,R.layout.content,null);  
        tv=(TextView) contentview.findViewById(R.id.tv);
        scrollView.addChild(contentview);
        
        final Handler handler = new Handler() {
        	public void handleMessage(Message message) {
        		String str = (String)message.obj;
        		tv.setText(str);
        		scrollView.onRefreshComplete();
        	}
        };
        scrollView.setonRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				Thread thread = new Thread(new Runnable() {
					
					@Override
					public void run() {
						try {
							Thread.sleep(3000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						Message message = handler.obtainMessage(0, ""+new Random().nextInt(100));
						handler.sendMessage(message);
					}
				});
				thread.start();
			}
		});
    }
}

 

 

 

<?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" >

    <com.example.refreshscrollview.RefreshScrollView
        android:id="@+id/scrollview1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#555555" >
    </com.example.refreshscrollview.RefreshScrollView>

</LinearLayout>

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:text="1" >
    </TextView>

</LinearLayout>