33

I have tried to use both ScrollView and ListView.

I figured out that if I use ListView and I click one of items let current fragment be replaced by next fragment and press back button to prev fragment. The scroll position of ListView will keep at same position. But if I use ScrollView, it will not.

I don't understand why they are different? And how can I make ScrollView keep its position after press back button?

Actually, I have searched some answer at StackOverflow. But I want to know the reasons and find an easier way to make ScrollView and ListView have same behavior.

Please help me! Thank you!

1 Answer 1

130

Fragments automatically save and restore the states of their Views, as long they have IDs assigned.

So if you assign an ID to your ScrollView, its scroll state can be restored:

<ScrollView android:id="@+id/scrollview"
    ...>
3
  • 1
    There is a lot of misinformation out there and this clears it up. For example, "you need to handle onSaveInstanceState/onRestoreInstanceState", that doesnt actually fix it, but the fact that you added an ID to the view when doing so, THAT fixed it.
    – Greg Ennis
    Commented Jun 27, 2017 at 2:56
  • you can read more here : inthecheesefactory.com/blog/…
    – Armin
    Commented Jun 8, 2018 at 5:25
  • my layout hierarchy is <layout> <RelativeLayout> <ScrollView> </ScrollView> <?RelativeLayout> </layout> And i am using live data . As suggested by u i gave id to my ScrollView , still position of scrollview is reset when pop back from other fragment . Any idea where i went wrong ?
    – Vivek
    Commented Aug 17, 2020 at 17:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.