Could I keep position of ScrollView after back to prev Fragment like ListView?
Asked Answered
R

1

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!

Rutheruthenia answered 27/9, 2014 at 2:7 Comment(0)
S
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"
    ...>
Singsong answered 9/9, 2016 at 13:27 Comment(3)
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.Roentgenograph
you can read more here : inthecheesefactory.com/blog/…Betancourt
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 ?Eusebiaeusebio

© 2022 - 2024 — McMap. All rights reserved.