手记

仿照ios回弹

公司需要需求上面跟这篇俩都是,适合刚学自定义同学,


/**
* zhao
*/

public class MyScrollView extends ScrollView {
//要操作View
private View mInnerView;
private float y;
private Rect normal = new Rect();
private boolean animationFlag = true;

public MyScrollView(Context context) {
super(context);
}

public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

/**
* 对象已经生成好了的时候,这个时候调用子类是合适的
*/
@Override
protected void onFinishInflate() {
int childCount = getChildCount();
if (childCount > 0) {
mInnerView = getChildAt(0);
}
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mInnerView == null) {
return super.onTouchEvent(ev);
} else {
commonTouch(ev);
}
return super.onTouchEvent(ev);
}

/**
* 事件分发
*
* @param ev
*/
private void commonTouch(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
y = ev.getY();
break;
case MotionEvent.ACTION_MOVE:
float prey = y == 0 ? ev.getY() : y;
float now = ev.getY();
int dataily = (int) (prey - now);
y = now;
Logger.verbose("otouzi", "dataily" + dataily + "now" + now + "----" + "prey" + prey);
//操作view进行拖动detail的一半
if (animationFlag) {
if (isneedMove()) {
//记录一下正常情况下位置
if (normal.isEmpty()) {
normal.set(mInnerView.getLeft(), mInnerView.getTop(), mInnerView.getRight(), mInnerView.getBottom());
}
mInnerView.layout(mInnerView.getLeft(), mInnerView.getTop() - dataily / 2, mInnerView.getRight(), mInnerView.getBottom() - dataily / 2);
}
}
break;
case MotionEvent.ACTION_UP:
y = 0;
if (isneedAnmion()) {
animateLayout();
}
break;
}
}

private void animateLayout() {
TranslateAnimation ta = new TranslateAnimation(0, 0, 0, normal.top - mInnerView.getTop());
ta.setDuration(500);
ta.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
animationFlag = false;
}

@Override
public void onAnimationEnd(Animation animation) {
mInnerView.clearAnimation();
mInnerView.layout(normal.left, normal.top, normal.right, normal.bottom);
normal.setEmpty();
animationFlag = true;
}

@Override
public void onAnimationRepeat(Animation animation) {

}
});
mInnerView.startAnimation(ta);
}

/**
* 布局移动
*
* @return
*/
public boolean isneedMove() {
//子view要操作view高度减去容器高度,scroollview的高度,
int offest = mInnerView.getMeasuredHeight() - getHeight();//getMeasuredHeight()是测量真实的
int scrollY = getScrollX();//这个是偏移量
if (scrollY == 0 || scrollY == offest) {
return true;
}
return false;
}

/**
* 判断是否要回到原来位置
*
* @return
*/
public boolean isneedAnmion() {
if (!normal.isEmpty()) {
return true;
} else {
return false;
}

}
}

原文链接:http://www.apkbus.com/blog-340477-76910.html

0人推荐
随时随地看视频
慕课网APP