當(dāng)我們編寫一些自定義的滑動控件時母怜,會用到一些api如scrollTo(),scrollBy(),getScrollX(), getScrollY()戏挡。由于常常會對函數(shù)getScrollX(), getScrollY()返回的值的含義產(chǎn)生混淆硕淑,尤其是正負(fù)關(guān)系彬坏,因此本文將使用幾幅圖來對這些函數(shù)進(jìn)行講解以方便大家記憶。
注意:調(diào)用View的scrollTo()和scrollBy()是用于滑動View中的內(nèi)容童太,而不是把某個View的位置進(jìn)行改變匈挖。如果想改變莫個View在屏幕中的位置,可以使用如下的方法康愤。
調(diào)用public void offsetLeftAndRight(int offset)用于左右移動方法或public void [offsetTopAndBottom]
(http://developer.android.com/reference/android/view/View.html#offsetTopAndBottom(int))(int offset)用于上下移動。
如:button.offsetLeftAndRignt(300)表示將button控件向左移動300個像素舶吗。
在注釋中說到征冷,該方法用于設(shè)置滾動視圖的位置,然后會調(diào)用onScrollChanged(int, int, int, int)方法誓琼,最后視圖會被刷新检激。那它是如何讓視圖滾動的呢肴捉?首先注意到在這個方法中有兩個變量:mScrollX、mScrollY叔收。
這兩個變量分別是視圖在水平和垂直方向的偏移量齿穗,
mScrollX: 該視圖內(nèi)容相當(dāng)于視圖起始坐標(biāo)的偏移量, X軸方向
mScrollY: 該視圖內(nèi)容相當(dāng)于視圖起始坐標(biāo)的偏移量饺律, Y軸方向
分別通過getScrollX() 和getScrollY()方法獲得窃页。
scrollTo()
說明:在當(dāng)前視圖內(nèi)容偏移至(x , y)坐標(biāo)處,即顯示(可視)區(qū)域位于(x , y)坐標(biāo)處复濒。
/**
* 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) {
//偏移位置發(fā)生了改變
if (mScrollX != x || mScrollY != y) {
int oldX = mScrollX;
int oldY = mScrollY;
mScrollX = x; //賦新值脖卖,保存當(dāng)前便宜量
mScrollY = y;
//回調(diào)onScrollChanged方法
onScrollChanged(mScrollX, mScrollY, oldX, oldY);
if (!awakenScrollBars()) {
invalidate(); //一般都引起重繪
}
}
}
sctollBy
public voidscrollBy(int x, int y)
說明:在當(dāng)前視圖內(nèi)容繼續(xù)偏移(x , y)個單位,顯示(可視)區(qū)域也跟著偏移(x,y)個單位巧颈。
/**
* 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
*/
// 看出原因了吧 畦木。。 mScrollX 與 mScrollY 代表我們當(dāng)前偏移的位置 砸泛, 在當(dāng)前位置繼續(xù)偏移(x ,y)個單位
public void scrollBy(int x, int y) {
scrollTo(mScrollX + x, mScrollY + y);
}
總結(jié):scrollTo()指的是移動到制定的(x,y)位置十籍,而scrollBy(x,y)指的是,在當(dāng)前位置在移動(x,y)個位置