Android系統手機屏幕的左上角為坐標系,同時y軸方向與笛卡爾坐標系的y軸方向想反。提供了
getLeft(),
getTop(),
getBottom(),
getRight()
這些API來獲取控件在Parent中的相對位置。
同時也提供了
getLocalVisibleRect()
getGlobalVisibleRect()
getLocationOnScreen()
getLocationInWindow()
這些API來獲取控件在屏幕中的絕對位置。詳情可參考:android應用程序中獲取view的位置
如果要將View中的內容滾動到相應到指定位置,可以使用這些API
scrollTo()
scrollBy()
如果要改變整個View在屏幕中的位置,可以使用下列API:
offsetLeftAndRight(int offset) // 用於左右移動 offsetTopAndBottom(int offset) // 用於上下移動
下面簡要總結一下scrollTo(),scrollBy(),getScrollX(), getScrollY()這些方法
scrollTo(int x, int y) 是將View中內容滑動到相應的位置,參考的坐標系原點為parent View的左上角。
調用scrollTo(100, 0)表示將View中的內容移動到x = 100, y = 0的位置,如下圖所示。注意,圖中黃色矩形區域表示的是一個parent View,綠色虛線矩形為parent view中的內容。一般情況下兩者的大小一致,本文為了顯示方便,將虛線框畫小了一點。圖中的黃色區域的位置始終不變,發生位置變化的是顯示的內容。
同理,scrollTo(0, 100)的效果如下圖所示:
scrollTo(100, 100)的效果圖如下:
若函數中參數為負值,則子View的移動方向將相反。
關於scrollTo()方法中參數值為正,卻向左移動,參數值為負,卻向右移動(這地方確實很怪)的一些理解:
scrollTo()方法本身滾動的是View的內容,View本身位置不變。可以將該View想象成一個帶滾動條的窗體,我們以滾動條作為參照物:
當水平滾動條向右移動時,原本窗體顯示的內容向左移動,比方說水平滾動條向右移動了100的距離,同樣的窗體顯示的內容就向左移動了100的距離,這個時候也就是scrollTo(100, 0);
當滾動條向下移動時,原本窗體顯示的內容應向上移動,比方說垂直滾動條向下移動了100的距離,同樣的窗體顯示的內容就向上移動了100的距離,這個時候也就是scrollTo(0, 100);
這也就解釋了為什么scrollTo()方法中參數大於0,View向左移動,參數小於0,View向右移動。
scrollBy(int x, int y)其實是對scrollTo的包裝,移動的是相對位置。 scrollTo(int x, int y)的源碼和scrollBy(int x, int 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<pre name="code" class="java"> /** * 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(); } } }
public void scrollBy(int x, int y) { scrollTo(mScrollX + x, mScrollY + y); }
可見,mScrollX和mScrollY是View類中專門用於記錄滑動位置的變量。這兩個函數最終調用onScrollChanged()函數,感興趣者可以參考他們的源代碼。
理解了scrollTo(int x, int y)和scrollBy(int x, int y)的用法,就不難理解getScrollX() 和getScrollY()。這兩個函數的源碼如下所示:
/** * Return the scrolled left position of this view. This is the left edge of * the displayed part of your view. You do not need to draw any pixels * farther left, since those are outside of the frame of your view on * screen. * * @return The left edge of the displayed part of your view, in pixels. */ public final int getScrollX() { return mScrollX;
/** * Return the scrolled top position of this view. This is the top edge of * the displayed part of your view. You do not need to draw any pixels above * it, since those are outside of the frame of your view on screen. * * @return The top edge of the displayed part of your view, in pixels. */ public final int getScrollY() { return mScrollY; }