32

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!

Azure Chen
  • 859
  • 1
  • 12
  • 21

1 Answers1

127

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"
    ...>
Floern
  • 33,559
  • 24
  • 104
  • 119
  • 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 Jun 27 '17 at 02:56
  • you can read more here : https://inthecheesefactory.com/blog/fragment-state-saving-best-practices/en – Armin Jun 08 '18 at 05:25
  • 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 reset when pop back from other fragment . Any idea where i went wrong ? – Vivek Aug 17 '20 at 17:25