1.使用scrollTo/scrollBy 操作简单,适用于对View内容的滑动:
scrollBy实际上是调用scrollTo方法,实现了基于当前位置的相对滑动,scrollTo则实现了基于所传递参数的绝对滑动。这个方法只能改变View内容的位置。
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);
}
在滑动过程中,mScrollX的值总是等于View的左边缘和View内容左边缘在水平方向的距离,而mScrollY的值总是等于View的上边缘和View内容上边缘在竖直方向的距离。
2.使用动画,操作简单主要适用于没有交互的View和实现复杂的动画效果
View动画不能真正的改变View的位置,使用属性动画可以解决这个问题,属性动画只能在android3.0以上的版本使用
属性动画:
ObjectAnimator.ofFloat(target,"translationX",0,100).setDuration(100).start();
3.改变布局参数,操作稍微复杂,适用于有交互的View
重新设置一个View的LayoutParams的方法(把一个button右移100px)
MarginLayoutParams params=(MarginLayoutParams)btn.getLayoutParams();
params.leftMargin+=100;
btn.requestLayout();