1. offsetLeftAndRight() 和 offsetTopAndBottom() (推荐)
- 实现的是对view的移动
- offsetLeftAndRight(int offset): 水平方向挪动View,offset为正则x轴正向移动,getLeft()和getRight()会变。
- offsetTopAndBottom(int offset): 垂直方向挪动View,offset为正则y轴正向移动,getTop()和getBottom会变。
2. scrollBy() 和 scrollTo() (推荐)
- 对View内容的移动
- scrollBy() :位移指定的偏移量
- scrollTo() :位置到指定的位置
3. translationX 和 translationY
- 实现的是对view的移动
- 相对于left,top,在view的平移过程中,left和top始终等于view初始状态时的值,只是x,y和translationX,translationY会发生改变,
- translationX:代表View平移的水平距离;
- translationY:代表View平移的垂直距离;
4.更改LayoutParams属性(不推荐)
示例
表示将view向右移动了100px
MarginLayoutParams params = (MarginLayoutParams) mButton.getLayoutParams();
params.leftMargin += 100;
// 请求重新对View进行measure、layout
mButton.requestLayout();
5.使用Scroller来实现平滑滑动
示例(模板代码)
本质依旧是调用了scrollTo()方法
Scroller scroller = new Scroller(mContext);
private void smoothScrollTo(int dstX, int dstY) {
int scrollX = getScrollX();
int scrollY = getScrollY();
int deltaX = dstX - scrollX;
int deltaY = dstY - scrollY;
scroller.startScroll(scrollX, scrollY, deltaX, deltaY, 1000);
invalidate();
}
@Override
public void computeScroll() {
if (scroller.computeScrollOffset()) {
scrollTo(scroller.getCurrX(), scroller.getCurY());
// 用于在非UI线程中更新用户界面
postInvalidate();
}
}
- 调用smoothScrollTo()方法开始执行滚动
- invalidate() 回调computeScroll()
- computeScroll()中的computeScrollOffset()方法为CurrX和CurrY赋值,如果动画未执行完成,返回true,否则返回false
- postInvalidate() 中再次调用computeScroll(),直至动画完成,实现平滑移动