关于Scrollview.scrollTo()不生效的问题

项目中遇到的需求是界面打开时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.scrollTo()不生效的问题)