关于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);           
    }
});

发布了13 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/old_land/article/details/79713181