ios里面所有的scrollview都是彈性滑動昼蛀,而安卓里面則沒有這個效果弯院,但是UE要求和Ios的效果一樣敬察,所以只能自己實現(xiàn)漠畜。
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
/**
* Data:2019/4/3-下午4:49
* Author:zxf
**/
public class DemoScrollView extends NestedScrollView {
private Rect normal = new Rect();// 矩形币他,保存scrollview原始位置
private boolean isScrolledToTop = true;
private boolean isScrolledToBottom;
float currentY=0;
float distanceY=0;
private View mInner;
public DemoScrollView(@NonNull Context context) {
super(context);
}
public DemoScrollView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public DemoScrollView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (getScrollY() == 0) { // 小心踩坑1: 這里不能是getScrollY() <= 0
isScrolledToTop=true;
isScrolledToBottom=false;
} else if (getScrollY() + getHeight() - getPaddingTop()-getPaddingBottom() == getChildAt(0).getHeight()) {
isScrolledToTop=false;
isScrolledToBottom=true;
} else {
isScrolledToTop=false;
isScrolledToBottom=false;
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
if (getChildCount()>0)
mInner= (ViewGroup) getChildAt(0);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()){
case MotionEvent.ACTION_DOWN:
currentY= ev.getY();
//finalY=ev.getY();
break;
case MotionEvent.ACTION_MOVE:
distanceY= currentY-ev.getY();
if (normal.isEmpty()){
normal.set(mInner.getLeft(), mInner.getTop(),mInner.getRight(), mInner.getBottom());
}
//到達最頂端
if (isScrolledToTop || isScrolledToBottom){
mInner.layout(mInner.getLeft(), (mInner.getTop()-(int)distanceY/10),mInner.getRight(), (int) (mInner.getBottom()-(int)distanceY/10));
}
break;
case MotionEvent.ACTION_UP:
distanceY=0;
//彈性動畫恢復到原位置
TranslateAnimation translateAnimation=new TranslateAnimation(0,0,mInner.getTop(),normal.top);
translateAnimation.setDuration(100);
mInner.startAnimation(translateAnimation);
mInner.layout(normal.left, normal.top, normal.right, normal.bottom);
normal.setEmpty();
break;
}
return super.dispatchTouchEvent(ev);
}
}
在dispatchTouchEvent 方法中對事件,滑動位置憔狞,view的位置進行處理處理蝴悉。
在ACTION_UP中使用動畫恢復view的位置,將矩形置空瘾敢。效果和ios的差不多