当前位置:   article > 正文

android ScrollView smoothScrollTo源码的一点理解

android ScrollView smoothScrollTo源码的一点理解

项目中用到smoothScrollTo,作为一个老程序员有点汗颜,还真是不知道原理是啥,于是在网络上搜索一番,没有看到理想的结果。于是乎静下心来去看源码吧。

  1. /**
  2. * Like {@link #scrollTo}, but scroll smoothly instead of immediately.
  3. *
  4. * @param x the position where to scroll on the X axis
  5. * @param y the position where to scroll on the Y axis
  6. */
  7. public final void smoothScrollTo(int x, int y) {
  8. smoothScrollBy(x - mScrollX, y - mScrollY);
  9. }
首先先搞清楚这里边的几个参数的含义:先说x,和y,这两个传入的参数就是你想要移动到的位置,这个位置就你要移动到的位置,当然是相对于ScrollView左上角的位置来说。mScrollX和mScrollY就是当前ScrollView的偏移量,也是相对于ScrollView的坐上角来说的,这两项的差值就是要滚动到的位置相对于当前ScrollView显示的左上角的坐标的一个相对位置。下面在放上smoothScrollBy的源码

  1. /**
  2. * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
  3. *
  4. * @param dx the number of pixels to scroll by on the X axis
  5. * @param dy the number of pixels to scroll by on the Y axis
  6. */
  7. public final void smoothScrollBy(int dx, int dy) {
  8. if (getChildCount() == 0) {
  9. // Nothing to do.
  10. return;
  11. }
  12. long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
  13. if (duration > ANIMATED_SCROLL_GAP) {
  14. final int height = getHeight() - mPaddingBottom - mPaddingTop;
  15. final int bottom = getChildAt(0).getHeight();
  16. final int maxY = Math.max(0, bottom - height);
  17. final int scrollY = mScrollY;
  18. dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY;
  19. mScroller.startScroll(mScrollX, scrollY, 0, dy);
  20. postInvalidateOnAnimation();
  21. } else {
  22. if (!mScroller.isFinished()) {
  23. mScroller.abortAnimation();
  24. if (mFlingStrictSpan != null) {
  25. mFlingStrictSpan.finish();
  26. mFlingStrictSpan = null;
  27. }
  28. }
  29. scrollBy(dx, dy);
  30. }
  31. mLastScroll = AnimationUtils.currentAnimationTimeMillis();
  32. }

首先说第8行,很简单,如果ScrollView没有包含任何东西,则什么都处理。(当然了,没有东西滚动毛线!)。然后说一下AnimationUtils.currentAnimationTimeMillis(),这个是获取从开机到现在的毫秒数。maxY计算的是超出ScrollView能够显示的那一部分的长度。dy计算出来的就是要滑动的距离。当然有人会问为什么还有判断if (duration > ANIMATED_SCROLL_GAP),这里是判断当前scrollView是否在滚动中,系统默认的滚动时间是250毫秒。我看网上很多人在问为什么设置的smoothScrollTo没有效果,就是因为计算出来的那个dy是0,这样就不会滚动了。所以解决这个问题还是要看自己设置的那个值为啥不对吧。

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

闽ICP备14008679号