1.使用 scrollTo/scrollBy
scrollBy實際上也是調用了scrollTo方法。
scrollBy實現了基于當前位置的相對滑動,scrollTo則實現了基于所傳參數的絕對滑動。
scrollTo和scrollBy只能改變View內容的位置而不能改變View在布局中的位置。
源碼
當View左邊緣在View內容的左邊緣的右邊時,mScrollX為正值,反之為負值;當View的上邊緣在View內容上邊緣的下邊時,mScrollY為正值,反之為負值。換句話說,如果從左向右滑動,那么mScrollX為負值,反之為正值:如果從下往上滑動,那么mScrollY為負值,反之為正值。
2.使用動畫
使用動畫來移動View,主要是操作View的translationX和translationY屬性,既可以用傳統的View動畫,也可以采用屬性動畫。
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<translate
android:duration="1000"
android:fromXDelta="0"
android:fromYDelta="0"
android:interpolator="@android:anim/linear_interpolator"
android:toXDelta="100"
android:toYDelta="100" />
</set>
ObjectAnimator.ofFloat(targetView, "translationX", 0, 100).setDuration(100).start();
View動畫是對View的影像操作,它并不能真正改變View的位置參數,包括寬高,動畫后的狀態保留必須將fillAfter屬性設置為true。屬性動畫不存在這個問題
3.改變布局參數
即改變LayoutParams,比如一個按鈕向右平移100px
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) mBtn.getLayoutParams();
layoutParams.leftMargin += 100;
mBtn.requestLayout();
//或者 mBtn.setLayoutParams(layoutParams);
4.三種方式的對比總結
- scrollT/scrollBy:操作簡單,適合對View內容的滑動
- 動畫:操作簡單,適用于實現復雜的動畫效果,View動畫適用于沒有交互的View,屬性動畫沒有明顯缺點
- 改變布局參數:稍復雜,適用于有交互的View