有弹性的scollview

这是一个实现反弹效果的自定义ScrollView,通过监听触摸事件并处理滑动,实现上滑时视图回弹的动画效果。
摘要由CSDN通过智能技术生成
package com.jmheart.view.scollview;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.ScrollView;

/**
 * @author liujie
 * 
 * 反弹ScrollView
 */
public class CustomerScrollView extends ScrollView {

	private Context mContext;
	private View mView;
	private Rect mRect = new Rect();
	private float y;

	public CustomerScrollView(Context context) {
		super(context);
		this.mContext = context;
	}

	public CustomerScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.mContext = context;
	}

	public CustomerScrollView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.mContext = context;
	}

	@Override
	protected void onFinishInflate() {
		if (getChildCount() > 0) {
			this.mView = getChildAt(0);
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if (mView == null) {
			return super.onTouchEvent(ev);
		} else {
			commOnTouchEvent(ev);
		}
		return super.onTouchEvent(ev);
	}

	private void commOnTouchEvent(MotionEvent ev) {
		int action = ev.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			y = ev.getY();
			break;
		case MotionEvent.ACTION_UP:
			if (isNeedAnimation()) {
				animation();
			}
			break;
		case MotionEvent.ACTION_MOVE:
			final float preY = y;
			float nowY = ev.getY();
			int deltaY = (int) (preY - nowY);
			scrollBy(0, deltaY);
			y = nowY;
			if (isNeedMove()) {
				if (mRect.isEmpty()) {
					mRect.set(mView.getLeft(), mView.getTop(),
					mView.getRight(), mView.getBottom());
				}
				if (mView.getTop() - deltaY < 150
					&& mView.getTop() - deltaY > -150) {
					mView.layout(mView.getLeft(), mView.getTop() - deltaY,
					mView.getRight(), mView.getBottom() - deltaY);
				}
			}
			break;
		default:
			break;
		}
	}

	private boolean isNeedMove() {
		int offset = mView.getMeasuredHeight() - getHeight();
		int scrollY = getScrollY();
		if (scrollY == 0 || scrollY == offset) {
			return true;
		}
		return false;
	}

	private boolean isNeedAnimation() {
		return !mRect.isEmpty();
	}

	private void animation() {
		TranslateAnimation ta = new TranslateAnimation(0, 0, mView.getTop(),
				mRect.top);
		ta.setDuration(200);
		mView.startAnimation(ta);
		mView.layout(mRect.left, mRect.top, mRect.right, mRect.bottom);
		mRect.setEmpty();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值