项目中遇到的需求是界面打开时scrollview滚动到上次选中的位置,结果在调用Scrollview.scrollTo()时代码不生效。
查看Scrollview源码发现在创建时有自己的动画。
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
mIsLayoutDirty = false;
// Give a child focus if it needs it
if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
scrollToChild(mChildToScrollTo);
}
mChildToScrollTo = null;
if (!isLaidOut()) {
if (mSavedState != null) {
mScrollY = mSavedState.scrollPosition;
mSavedState = null;
} // mScrollY default value is "0"
final int childHeight = (getChildCount() > 0) ? getChildAt(0).getMeasuredHeight() : 0;
final int scrollRange = Math.max(0,
childHeight - (b - t - mPaddingBottom - mPaddingTop));
// Don't forget to clamp
if (mScrollY > scrollRange) {
mScrollY = scrollRange;
} else if (mScrollY < 0) {
mScrollY = 0;
}
}
// Calling this with the present values causes it to re-claim them
scrollTo(mScrollX, mScrollY);
}所在再Scrollview创建完成时在执行scrollTo(),方法才生效。
1、调用View.post或View.postDelayed
mScrollview.post(new Runnable() {
@Override
public void run() {
mScrollview.scrollTo(0, mYPosition);
}
});2、获取scrollView 的ViewTreeObserver 给Scrollview注册addOnGlobalLayoutListener
ViewTreeObserver vto = mScrollview.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
mScrollview.scrollTo(0, mYPosition);
}
});
本文解决了一个界面需求问题:当界面加载时,ScrollView无法自动滚动到上次选中的位置。通过分析ScrollView源码,发现其内部存在默认动画导致直接调用scrollTo()无效。文章提供了两种解决方案:一是使用View.post()延迟执行滚动操作;二是利用ViewTreeObserver监听全局布局变化。
1943

被折叠的 条评论
为什么被折叠?



