当前位置:   article > 正文

HorizontalScrollView重新layout之后自动滑动初始位置问题解决_horizontalscrollview滑动复原位置

horizontalscrollview滑动复原位置

HorizontalScrollView在重新layout时,有时候会自动滑动到其他位置,这是由于他的后代view获取到焦点导致的,来让我们从代码层面看清这个问题:

  1. @Override
  2. protected void onLayout(boolean changed, int l, int t, int r, int b) {
  3. int childWidth = 0;
  4. int childMargins = 0;
  5. if (getChildCount() > 0) {
  6. childWidth = getChildAt(0).getMeasuredWidth();
  7. LayoutParams childParams = (LayoutParams) getChildAt(0).getLayoutParams();
  8. childMargins = childParams.leftMargin + childParams.rightMargin;
  9. }
  10. final int available = r - l - getPaddingLeftWithForeground() -
  11. getPaddingRightWithForeground() - childMargins;
  12. final boolean forceLeftGravity = (childWidth > available);
  13. layoutChildren(l, t, r, b, forceLeftGravity);
  14. mIsLayoutDirty = false;
  15. // Give a child focus if it needs it
  16. //就是在这一行,scrollView自动滑动到那个有焦点的view的位置
  17. if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
  18. scrollToChild(mChildToScrollTo);
  19. }
  20. mChildToScrollTo = null;
  21. if (!isLaidOut()) {
  22. final int scrollRange = Math.max(0,
  23. childWidth - (r - l - mPaddingLeft - mPaddingRight));
  24. if (mSavedState != null) {
  25. mScrollX = isLayoutRtl()
  26. ? scrollRange - mSavedState.scrollOffsetFromStart
  27. : mSavedState.scrollOffsetFromStart;
  28. mSavedState = null;
  29. } else {
  30. if (isLayoutRtl()) {
  31. mScrollX = scrollRange - mScrollX;
  32. } // mScrollX default value is "0" for LTR
  33. }
  34. // Don't forget to clamp
  35. if (mScrollX > scrollRange) {
  36. mScrollX = scrollRange;
  37. } else if (mScrollX < 0) {
  38. mScrollX = 0;
  39. }
  40. }
  41. // Calling this with the present values causes it to re-claim them
  42. scrollTo(mScrollX, mScrollY);
  43. }


而mChildToScrollTo这个view是在requestChildFocus中赋值的,

  1. @Override
  2. public void requestChildFocus(View child, View focused) {
  3. if (!mIsLayoutDirty) {
  4. scrollToChild(focused);
  5. } else {
  6. // The child may not be laid out yet, we can't compute the scroll yet
  7. mChildToScrollTo = focused;
  8. }
  9. super.requestChildFocus(child, focused);
  10. }


解决办法 :

覆写父类方法onLayout,就可以解决这个问题

  1. @Override
  2. protected void onLayout(boolean changed, int l, int t, int r, int b) {
  3. final int tempScrollX = getScrollX();
  4. super.onLayout(changed, l, t, r, b);
  5. final int scrollX = getScrollX();
  6. if (tempScrollX != scrollX) {
  7. this.scrollTo(tempScrollX, 0);
  8. }
  9. }





声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/312700
推荐阅读
  

闽ICP备14008679号