View的滑动常用的有三种方式:第一种是通过View本身提供的scrollTo/scrollBy方法来实现滑动;第二种是通过动画给View施加平移效果来实现滑动;第三种是通过改变View的LayoutParams使得View重新布局从而实现滑动。
1.使用scrollTo/scrollBy
先看看这两个方法的源码:
/**
*Set the scrolled position of your view.This will cause a call to{@link #onScrollChanged(int,int,int,int)}and the view will be invalidated.
*@param x the x position to scroll to
*@param y the y position to scroll to
*/
public void scrollTo(int x,int y){
if(mScrollX !=X || mScrollY != Y){
int oldX = mScrollX;
int oldY=mScrollY;
mScrollX=x;
mScrollY=y;
invalidateParentCaches();
onScrollChanged(mScrollX,mScrollY,oldX,oldY);
if(!awakenScrollBars()){
postInvalidateOnAnimation();
}
}
}
/**
*Move the scrolled position of your view.This will cause a call to{@link #onScrollChanged(int,int,int,int)}and the view will be invalidated.
*@param x the amount of pixels to scroll by horizontally
*@param y the amount of pixels to scroll by vertically
*/
public void scrollBy(int x,int y){scrollTo(mScrollX+x,mScrollY+y);
}
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true" android:zAdjustment="normal"> <translate android:duration="100" android:fromXDelta="0" android:fromYDelta="0" android:interpolator="android:anim/linear_interpolator" android:toXDelta="100" android:toYDelta="100"/> </set>如果采用属性动画就更简单了,以下代码可以将一个View在100ms内从原始位置向右平移100像素
ViewGroup.MarginLayoutParams marginLayoutParams= (ViewGroup.MarginLayoutParams) mButton.getLayoutParams(); marginLayoutParams.width+=100; marginLayoutParams.leftMargin+=100;mButton.requestLayout();//或者mButton.setLayoutParams(marginLayoutParams);