'Android: How to scroll a ScrollView inside a Fragment which is part of an ViewPagerAdapter for a ViewPager2

I'm using a ViewPager2 with a ViewPagerAdapter. This adapter includes Fragments. The layout of this Fragment has a ScrollView.

What I want to do is to scroll to a certain position once the fragment is shown. I have tried several things but sv.scrollTo(x,y) does not have any effect. Only when I trigger it via a button from the MainActivity then the ScrollView scrolls.

Things I have tried:

  1. Inside Fragment class in method onViewCreated:
ViewTreeObserver vto = sv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
   @Override
   public void onGlobalLayout() {
       sv.scrollTo(0, iScrollPosition * tv.getLineHeight());
   }
});
  1. Inside Fragment class at the end of onViewCreated:
Runnable r = new Runnable() {
    public void run() {
        sv.scrollTo(0, iScrollPosition * tv.getLineHeight());              
    }
};
  1. Override inside Fragment class onStart
public void onStart() {
   super.onStart();
   sv.scrollTo(0, iScrollPosition * tv.getLineHeight());  
}
  1. In MainActivity in the function mViewPager.registerOnPageChangeCallback

  2. In the ViewPagerAdapter:

@NonNull @Override public Fragment createFragment(int position) {

Nothing has worked so far. It seems that I need a function which is trigged once the layout is completely drawn. Like the onload event in HTML.

Does anyone can give me a hint? I run out of ideas... Thanks.



Solution 1:[1]

You're using the OnGlobalLayoutListener.You can simply remove that.

If you still want to use it, then remove it after applying it to the view like this:

vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
   @Override
   public void onGlobalLayout() {
       vto.removeOnGlobalLayoutListener(this);

       //Your code here
       sv.scrollTo(0, iScrollPosition * tv.getLineHeight());
   }
});

It's the common thing used everywhere & everytime whenever you are observing the view layout changees. The code you put inside will run everytime whenever the layout is changing its size or any properties related to that.

You've not removed the listener so it's calling multiple times and causing the problem.

Just try it and let me know if it helped or not. :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dev4Life