Home > front end >  Why does the scrollTo method inside RecyclerView not have any effect?
Why does the scrollTo method inside RecyclerView not have any effect?

Time:01-19

I have a RecyclerView with a LinearLayoutManager set to horizontal. As you can see in the code below, I am trying to animate from the first item of the list to the last item of the list using ValueAnimator. In my usage, I don't need to use the scrollBy or scrollToPosition methods. I need to use the scrollTo method, but it has no effect. Why is this the case?

ValueAnimator valueAnimator = ValueAnimator.ofInt(0,activityMainBinding.rv.computeHorizontalScrollOffset());
valueAnimator.setDuration((100000)); valueAnimator.setStartDelay(1500);
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(valueAnimator1 -> { 
activityMainBinding.rv.scrollTo((int) valueAnimator1.getAnimatedValue(), 0); });
valueAnimator.start();

CodePudding user response:

If you look inside of RecyclerView, you will see the following for scrollTo():

@Override
public void scrollTo(int x, int y) {
    Log.w(TAG, "RecyclerView does not support scrolling to an absolute position. "
              "Use scrollToPosition instead");
}

In fact, you should see that text in your logcat.

You say that you must use scrollTo(), but that doesn't seem possible. I suggest that you review this requirement to understand why scrollTo() is required.

I will also suggest that RecyclerView#computeHorizontalScrollOffset() is not doing what you think it is doing.

  • Related