记得老版本的京东客户端的首页有一个下拉一张卷轴图片展示活动页面的效果,当时觉得展示效果很好。不过不知道为何最近的版本为何没有出现过。正好最近看了V4包中ViewDragHelper的内容,发现用来实现这个效果挺简单的,便凭着记忆简单实现了一下,最终效果如下:
整个页面的根布局就是利用ViewDragHelper实现的自定义ViewGroup。关于ViewDragHelper的知识可以参考鸿洋大神的文章。通过实现ViewDragHelper.CallCack的相关方法,定义了可竖直滚动的view,竖直滚动的范围。
@Override
public boolean tryCaptureView(View child, int pointerId) {
if (child == mDrawerView && !canScroll)
return false;
return child == mDrawerView;
}
@Override
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
mTopViewDragHelper.captureChildView(mDrawerView, pointerId);
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
return super.clampViewPositionHorizontal(child, left, dx);
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
return Math.max(Math.min(top, 0), -mDrawerView.getHeight() + sourceHeight);
}
手指松开时判断距离,如果滚动距离超过一半便到底部,否则返回原位置。
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
float movePercentage = (releasedChild.getHeight() + releasedChild.getTop()) / (float) releasedChild.getHeight();
int finalTop = (xvel >= 0 && movePercentage > 0.5f) ? 0 : -releasedChild.getHeight() + sourceHeight;
mTopViewDragHelper.settleCapturedViewAt(releasedChild.getLeft(), finalTop);
invalidate();
}
因为随着手指下拉,卷轴里面的内容是相对屏幕保持不动的,所以我们要通过回调,实时或得滚动的距离,通过layout方法相应调整卷轴的内容的view,从而实现视觉上的静止。
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
if (mOpenChangeListener != null) {
mOpenChangeListener.onShowHeightChanging(mDrawerView.getMeasuredHeight() + top);
}
}
上图mDrawerView.getMeasuredHeight() + top的值就是下图showHeight的值。
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
MarginLayoutParams cParams;
if (getChildCount() < 2)
return;
childViewContent = getChildAt(0);
cParams = (MarginLayoutParams) childViewContent.getLayoutParams();
cl = cParams.leftMargin;
ct = cParams.topMargin;
cr = cl + childViewContent.getMeasuredWidth();
cb = childViewContent.getMeasuredHeight() + ct;
childViewContent.layout(cl, ct + getMeasuredHeight() - showHeight, cr, cb + getMeasuredHeight() - showHeight);
View childViewScroll = getChildAt(1);
cParams = (MarginLayoutParams) childViewScroll.getLayoutParams();
childViewScroll.layout(cParams.leftMargin,
getMeasuredHeight() - childViewScroll.getMeasuredHeight(),
cParams.leftMargin + childViewScroll.getMeasuredWidth(),
getMeasuredHeight());
}