6

I have 2 Fragments A and B.

A contains a ScrollView, if I scroll down and press a button Fragment A gets replaced by Fragment B. Now i press the back-button and Fragment A comes back to the screen, but the ScrollView is not at the same position as it was when I switched to Fragment B.

But when I do the same with a Fragment (not a ListFragment!) that contains a ListView the scroll position is maintained.

Is there anything special I have to do with my ScrollView?!

Greetings, Daniel.

daniel m
  • 415
  • 6
  • 15

2 Answers2

23

Both ScrollView and NestedSrollView has inner class extended from BaseSavedState which saves state of scrollPosition. You merely need to give your scrolling view an id to save and restore it's instance state automatically (you do NOT need to call it manually).. See Could I keep position of ScrollView after back to prev Fragment like ListView?

ARiF
  • 1,079
  • 10
  • 23
Greg Ennis
  • 14,917
  • 2
  • 69
  • 74
  • my layout hierarchy is And i am using live data . As suggested by u i gave id to my ScrollView , still position of scrollview is rest when pop back from other fragment . Any idea where i went wrong ? – Vivek Aug 17 '20 at 14:26
  • Thank you for the great Answer! There is a common behavior for views to retain there state for configuration changes and back navigation. for example EditText will keep the input text on orientation changes and back presses to it. – Dor Solomon Aug 18 '21 at 09:58
0

As Nutomic said the position needs to be saved but even then, the ScrollView's height will be 0 in onCreate, onCreateView or onActivityCreated

I ended up using a OnPreDrawListener and it works very well.

scrollView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        scrollView.scrollTo(0, position);
        mView.getViewTreeObserver().removeOnPreDrawListener(this);
        return true;
    }
});
andrei
  • 2,934
  • 2
  • 23
  • 36
  • `onPreDraw()` is now more easy using Kotlin with Android KTX. `view.doOnPreDraw { actionToBeTriggered() }`. Checkout: https://github.com/android/android-ktx – Hemant Kaushik Mar 21 '18 at 06:58