Android v4 SwipeRefreshLayout的二次开发,支持背景层View一起滑动.

来源:互联网 发布:福利彩票选号软件 编辑:程序博客网 时间:2024/05/29 07:03

本人使用的是版本为21.0.2的v4包.这个版本的下拉和以前的版本不同,它下拉的时候会出现一个圆球,送手时 圆球会进行动画.SwipeRefreshLayout类包含了2个私有类,一个是MaterialProgressDrawable(最中心的动画);一个是CircleImageView(圆球),它继承了ImageView,而MaterialProgressDrawable继承了Drawable.所以MaterialProgressDrawable为CircleImageView所显示的内容.它在构造函数的时候调用了createProgressView()方法.来看关键代码:

private void createProgressView() {mCircleView = new CircleImageView(getContext(), CIRCLE_BG_LIGHT,CIRCLE_DIAMETER / 2);mProgress = new MaterialProgressDrawable(getContext(), this);mProgress.setBackgroundColor(CIRCLE_BG_LIGHT);mCircleView.setImageDrawable(mProgress);mCircleView.setVisibility(View.GONE);addView(mCircleView);}
这里开始讲如何将它支持下拉时,内容View一起滚动的效果类似Android-PullToRefresh,但又保留自带的动画效果.实现起来很简单.重写onLayout:

@Overrideprotected void onLayout(boolean changed, int left, int top, int right,int bottom) {final int width = getMeasuredWidth();final int height = getMeasuredHeight();if (getChildCount() == 0) {return;}if (mTarget == null) {ensureTarget();}if (mTarget == null) {return;}int circleWidth = mCircleView.getMeasuredWidth();int circleHeight = mCircleView.getMeasuredHeight();final View child = mTarget;final int childLeft = getPaddingLeft();int childTop = getPaddingTop();if (mCurrentTargetOffsetTop != -circleHeight&& mCurrentTargetOffsetTop < 0) {childTop += circleHeight + mCurrentTargetOffsetTop;} else if (mCurrentTargetOffsetTop != -circleHeight&& mCurrentTargetOffsetTop >= 0) {childTop += mCurrentTargetOffsetTop + circleHeight+ mCurrentTargetOffsetTop;}final int childWidth = width - getPaddingLeft() - getPaddingRight();final int childHeight = height - getPaddingTop() - getPaddingBottom();mCircleView.layout((width / 2 - circleWidth / 2),mCurrentTargetOffsetTop, (width / 2 + circleWidth / 2),mCurrentTargetOffsetTop + circleHeight);child.layout(childLeft, childTop, childLeft + childWidth, childTop+ childHeight);}
这样内容View就与下拉View同时滚动了.当然你也可以在onLayout中设置Imageview的位置,很简单吧.赶紧试试吧.

0 0
原创粉丝点击