一、使用scrollTo / scrollBy
scrollTo / scrollBy 只能改變View內(nèi)容的位置,而不能改變View在布局中的位置。
scrollTo:基于所傳遞參數(shù)的絕對滑動。
public void scrollTo(int x, int y)
例子:
//布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/main_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
//代碼
mMain_layout = (RelativeLayout)findViewById(R.id.main_layout);
mMain_layout.scrollTo(-+500, -+500); //注意負(fù)數(shù)前面要加"-+"
scrollBy:基于當(dāng)前位置的相對滑動。
public void scrollBy(int x, int y) {
scrollTo(mScrollX + x, mScrollY + y);
}
例子:
//布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/main_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
//代碼
mMain_layout = (RelativeLayout)findViewById(R.id.main_layout);
mMain_layout.scrollTo(-+100, 0); //注意負(fù)數(shù)前面要加"-+"
mMain_layout.scrollBy(-+400, -+500); //注意負(fù)數(shù)前面要加"-+"
View內(nèi)部有兩個滑動相關(guān)的屬性:mScrollX和mScrollY。
mScrollX:通過getScrollX()獲取,表示View左邊緣和View內(nèi)容左邊緣在水平方向的距離。當(dāng)View左邊緣在View內(nèi)容左邊緣的右邊時為正值(從右向左滑動),反之為負(fù)值(從左向右滑動)。
mScrollY:通過getScrollY()獲取,表示View上邊緣和View內(nèi)容上邊緣在豎直方向的距離。當(dāng)View上邊緣在View內(nèi)容上邊緣的下邊時為正值(從下向上滑動),反之為負(fù)值(從上向下滑動)。
二、使用動畫
使用動畫來移動View,主要是操作View的translationX和translationY屬性,既可以采用傳統(tǒng)的View動畫,也可以采用屬性動畫。
使用方法及工作原理將在"動畫"小節(jié)介紹。
例子:
View動畫:
<?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="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();
三、改變布局參數(shù)
改變布局參數(shù)即改變LayoutParams。
例子:
MarginLayoutParams params = (MarginLayoutParams)mButton1.getLayoutParams();
params.width += 100;
params.leftMargin += 100;
mButton1.requestLayout();
//或者 mButton1.setLayoutParams(params);
四、各種滑動方式的對比
scrollTo / scrollBy:操作簡單,適合對View內(nèi)容的滑動。
動畫:主要適用于沒有交互的View和實現(xiàn)復(fù)雜的動畫效果。
改變布局參數(shù):操作稍微復(fù)雜,適用于有交互的View。