Android滾動佈局ScrollView滾動到指定的View
阿新 • • 發佈:2019-01-10
本文用於在滾動佈局中,操作View到螢幕頂端位置:
Activity生命週期中,onStart, onResume, onCreate都不是真正View真正visible的時間點,真正的visible時間點是onWindowFocusChanged()函式被執行時。
備註:從onWindowFocusChanged被執行起,使用者可以與應用進行互動了,而這之前,對使用者的操作需要做一點限制。
擴充套件:如果想要做一個Activity一載入完畢,就觸發相應操作的話可以在onWindowFocusChanged()函式內操作
如果View還沒有visible,使用View的getWidth() 、getHeight() 方法來獲取該View的寬和高,返回的值為0。onWindowFocusChanged()內呼叫getWidth() 、getHeight() 方法可以正常獲取寬和高。
獲取距離
獲取View距離父容器的距離:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
y = view.getTop(); //頂部距離父容器的Y軸距離
}
方法原始碼
smoothScrollTo(x,y):
/**
* Like {@link #scrollTo}, but scroll smoothly instead of immediately.
*
* @param x the position where to scroll on the X axis
* @param y the position where to scroll on the Y axis
*/
public final void smoothScrollTo(int x, int y) {
smoothScrollBy(x - mScrollX, y - mScrollY);
}
使用方法
利用scrollView的smoothScrollTo()方法操作View:
scrollView.smoothScrollTo(0 ,y);