本文共 3454 字,大约阅读时间需要 11 分钟。
public class MyView extends View { int lastX; int lastY; Scroller mScroller; public MyView(Context context, AttributeSet attributeSet){ super(context, attributeSet); mScroller = new Scroller(context); } //6、2 属性动画一定要实现该属性的set方法 public void setWidth(int width){ getLayoutParams().width = width; requestLayout(); } public int getW(){ return getLayoutParams().width; } @Override public boolean dispatchTouchEvent(MotionEvent event) { Log.i("_tag","MyView dispatchTouchEvent"); return super.dispatchTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { Log.i("_tag","MyView onTouchEvent " + event.getAction()); int x = (int)event.getX(); int y = (int)event.getY(); switch(event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = x; lastY = y; break; case MotionEvent.ACTION_MOVE: int offsetX = x - lastX; int offsetY = y - lastY; //1、滑动方法1 ---> layout()// layout(getLeft() + offsetX, getTop() + offsetY, getRight() + offsetX, getBottom() + offsetY); //2、滑动方法2 ------> offsetLeftAndRight()// offsetLeftAndRight(offsetX);// offsetTopAndBottom(offsetY); //3、滑动方法3 -------> layoutParams// ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams();// layoutParams.leftMargin = getLeft() + offsetX;// layoutParams.topMargin = getTop() + offsetY;// setLayoutParams(layoutParams); //4、scrollBy是移动一定的偏移,scrollTo是移动到某个位置// ((View)getParent()).scrollBy(-offsetX, -offsetY); break; case MotionEvent.ACTION_UP: View viewGroup = ((View)getParent()); //5.1、使用 Scroller 结合 scrollTo() mScroller.startScroll(viewGroup.getScrollX(), viewGroup.getScrollY(), viewGroup.getScrollX(), viewGroup.getScrollY()); invalidate(); //6.1、属性动画 AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether( ObjectAnimator.ofInt(this, "width", getW(), 100), ObjectAnimator.ofFloat(this, "rotationX", 0, 360), ObjectAnimator.ofFloat(this, "rotationX", 0, 180), ObjectAnimator.ofFloat(this, "rotation", 0, -90), ObjectAnimator.ofFloat(this, "translationX", 0, 90), ObjectAnimator.ofFloat(this, "translationY", 0, 90), ObjectAnimator.ofFloat(this, "scaleX", 1, 1.5F), ObjectAnimator.ofFloat(this, "scaleY", 1, 0.5F), ObjectAnimator.ofFloat(this, "alpha", 1, 0.25F, 1) ); break; } return super.onTouchEvent(event);// return true; } //5.2、使用Scroller, 循环:invalidate()---> onDraw() ---> computeScroll() @Override public void computeScroll() { super.computeScroll(); //判断scroller是否执行完毕 if(mScroller.computeScrollOffset()){ ((View)getParent()).scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); invalidate(); } }}
转载地址:http://qhaji.baihongyu.com/