因为 只是基础功能 所以比较简单。说下实现基础吧 控制头布局和子布局的translationY 。
首先是初始化
mHeadView = new Head(context);
mHeadView.measure(0, 0);
mLayoutHeight = mHeadView.getMeasuredHeight();
addView(mHeadView);
mHeadView.setTranslationY(-mLayoutHeight);
mHeadView.changeStatus(Head.Status.pull_to_refresh);
mFootView = new Foot(context);
LayoutParams footParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
footParams.gravity = Gravity.BOTTOM;
addView(mFootView);
mFootView.setLayoutParams(footParams);
mFootView.changeStatus(Foot.Status.pull_to_load);
mFootView.setTranslationY(mLayoutHeight);
setBackgroundColor(getResources().getColor(android.R.color.white));
如上 讲头布局设置一个负的translation使之隐藏,底布局同理
然后是拦截
if (mHeadView.getTranslationY() == 0 || mFootView.getTranslationY() == 0) {
return false;
}
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastY = ev.getRawY();
break;
case MotionEvent.ACTION_MOVE:
float curY = ev.getRawY();
float dy = curY - mLastY;
if (dy > 0 && !ViewCompat.canScrollVertically(child, -1)) {
isPullUp = true;
return true;
}
if (dy < 0 && !ViewCompat.canScrollVertically(child, 1)) {
isPullUp = false;
return true;
}
mLastY = curY;
break;
}
在子布局不能滑动的时候拦截
处理自身的move事件
float curY = event.getRawY();
float dy = curY - mLastY;
if (isPullUp) {
float headTranslationY = mHeadView.getTranslationY();
headTranslationY += dy;
mHeadView.setTranslationY(headTranslationY);
float childTranslationY = child.getTranslationY();
childTranslationY += dy;
child.setTranslationY(childTranslationY);
} else {
float footTranslationY = mFootView.getTranslationY();
footTranslationY += dy;
mFootView.setTranslationY(footTranslationY);
float childTranslationY = child.getTranslationY();
childTranslationY += dy;
child.setTranslationY(childTranslationY);
}
mLastY = curY;
break;
手指抬起的操作
if (isPullUp) {
if (mHeadView.getTranslationY() > 0) {
mHeadView.setTranslationY(0);
child.setTranslationY(mLayoutHeight);
mHeadView.changeStatus(Head.Status.refreshing);
if (listener != null) listener.onRefresh();
} else {
resetHead();
}
} else {
if (mFootView.getTranslationY() < mLayoutHeight) {
mFootView.setTranslationY(0);
child.setTranslationY(-mLayoutHeight);
mFootView.changeStatus(Foot.Status.loading);
if (listener != null) listener.onLoadMore();
} else {
resetFoot();
}
}
核心代码就是上面了
全部代码请看github (https://github.com/fanyaopeng/CommonRefresh)