Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you correctly continue the fling of a ScrollView when adding children?

Context: I have a ScrollView that may have children added to its content view during a fling. Since the fling is configured with the height of the ScrollView contents before those children are added, if children get added then the fling stops itself (and actually scrolls backwards a bit because of overscroll) even though it hasn't reached the bottom of the contents.

I can possibly restart the fling using #fling(int velocity), but I can't figure out a way to get the current fling velocity or stop the current fling. Any ideas?

like image 900
Foxichu Avatar asked Jun 25 '15 20:06

Foxichu


1 Answers

To answer your questions from the prompt:

  • There are no APIs to get the current velocity of ScrollView.
  • You can stop the current fling by careful handling of touch events as described in a previous SO post.

Looking at the ScrollView source code, it uses an OverScroller to handle the fling events. There are two ways of approaching this:

  1. Use reflection to access the mScroller private field within ScrollView. Once you have accessed it you can get the current velocity through its public API: public float getCurrVelocity(); Using reflection is never ideal since you have to worry about it breaking across android versions, but a simple isolated usage can be relatively efficient.
  2. Override the fling() method in ScrollView and instantiate a OverScroller to keep track of the scrolling. If all goes well, your Overscoller will always be in the same state as the one within ScrollView.

Something like this:

@Override
public void fling(int velocityY)
{
    // Pass through fling to parent
    super.fling(velocityY);

    // Keep track of velocity using our own Overscoller instance
    mOurOverscroller = mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0,
    Math.max(0, bottom - height), 0, height/2);
}
like image 200
Trevor Carothers Avatar answered Sep 22 '22 22:09

Trevor Carothers