ANDROID仿淘宝商品浏览滑(拖)动查看详情界面

转自:http://dwtedx.com/itshare_311.html

由于目前的项目也是在做商城的应用、自然少不点商品的展示页、个人觉得淘宝的商品展示页非常不错、在网上找了很多资源、最后自己动集成了一个Demo、本Demo实现了Android类似于淘宝商品页展示的滑动效果(继续拖动,查看图文详情)、如果拖动了一半就会自动滑动到顶部、并带有动画效果、原理是通过两个ScrollView来实现的、上面的ScrollView放产品简介、下面的ScrollView放详细介绍、下面是应用简单的截图、具体效果大家可以下载源代码导入Eclipse查看

ANDROID仿淘宝商品浏览滑(拖)动查看详情界面_第1张图片


事件处理程序

private Handler handler = new Handler() {

	@Override
	public void handleMessage(Message msg) {
		if (mMoveLen != 0) {
			if (state == AUTO_UP) {
				mMoveLen -= SPEED;
				if (mMoveLen <= -mViewHeight) {
					mMoveLen = -mViewHeight;
					state = DONE;
					mCurrentViewIndex = 1;
				}
			} else if (state == AUTO_DOWN) {
				mMoveLen  = SPEED;
				if (mMoveLen >= 0) {
					mMoveLen = 0;
					state = DONE;
					mCurrentViewIndex = 0;
				}
			} else {
				mTimer.cancel();
			}
		}
		requestLayout();
	}

};

重写dispatchTouchEvent方法

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
	switch (ev.getActionMasked()) {
	case MotionEvent.ACTION_DOWN:
		if (vt == null)
			vt = VelocityTracker.obtain();
		else
			vt.clear();
		mLastY = ev.getY();
		vt.addMovement(ev);
		mEvents = 0;
		break;
	case MotionEvent.ACTION_POINTER_DOWN:
	case MotionEvent.ACTION_POINTER_UP:
		// 多一只手指按下或抬起时舍弃
		//将要到来的第一个事件move,防止多点拖拽的bug
		mEvents = -1;
		break;
	case MotionEvent.ACTION_MOVE:
		vt.addMovement(ev);
		if (canPullUp && mCurrentViewIndex == 0 
			&& mEvents == 0) {
			mMoveLen  = (ev.getY() - mLastY);
			// 防止上下越界
			if (mMoveLen > 0) {
				mMoveLen = 0;
				mCurrentViewIndex = 0;
			} else if (mMoveLen < -mViewHeight) {
				mMoveLen = -mViewHeight;
				mCurrentViewIndex = 1;

			}
			if (mMoveLen < -8) {
				// 防止事件冲突
				ev.setAction(MotionEvent.ACTION_CANCEL);
			}
		} else if (canPullDown && 
			mCurrentViewIndex == 1 && mEvents == 0) {
			mMoveLen  = (ev.getY() - mLastY);
			// 防止上下越界
			if (mMoveLen < -mViewHeight) {
				mMoveLen = -mViewHeight;
				mCurrentViewIndex = 1;
			} else if (mMoveLen > 0) {
				mMoveLen = 0;
				mCurrentViewIndex = 0;
			}
			if (mMoveLen > 8 - mViewHeight) {
				// 防止事件冲突
				ev.setAction(MotionEvent.ACTION_CANCEL);
			}
		} else
			mEvents  ;
		mLastY = ev.getY();
		requestLayout();
		break;
	case MotionEvent.ACTION_UP:
		mLastY = ev.getY();
		vt.addMovement(ev);
		vt.computeCurrentVelocity(700);
		// 获取Y方向的速度
		float mYV = vt.getYVelocity();
		if (mMoveLen == 0 || mMoveLen == -mViewHeight)
			break;
		if (Math.abs(mYV) < 500) {
			// 速度小于一定值的时候当作静止释放
			//这时候两个View往哪移动取决于滑动的距离
			if (mMoveLen <= -mViewHeight / 2) {
				state = AUTO_UP;
			} else if (mMoveLen > -mViewHeight / 2) {
				state = AUTO_DOWN;
			}
		} else {
			// 抬起手指时速度方向决定两个View往哪移动
			if (mYV < 0)
				state = AUTO_UP;
			else
				state = AUTO_DOWN;
		}
		mTimer.schedule(2);
		try {
			vt.recycle();
		} catch (Exception e) {
			e.printStackTrace();
		}
		break;

	}
	super.dispatchTouchEvent(ev);
	return true;
}

你可能感兴趣的:(自定义控件)