Saving the position of a ScrollView inside a Fragment

I thought of writing a post about how to save the position of a ScrollView when I read the Bhavin’s comment in the post Tab Layout in Android with ActionBar and Fragment.
Bhavin asked how one could restore the position of a scrollview switching between a tab and the other.

Here is a possible solution:

  1. create an Android Project, package eu.lucazanini.scrollingtab and not starting Activity
  2. replace the file AndroidManifest.xml
  3. edit the file res/values/strings.xml, in order to manage the tabs and their content
  4. create the il file res/layout/main.xml, it should be the default one
  5. create the files res/layout/tab1.xml e res/layout/tab2.xml, they are the layout of the 2 tabs

    in the second layout you see a ScrollView containing a TextView with a very long text
  6. create the class eu/lucazanini/scrollingtab/, note that the labels of the tabs will be capitalized and that eventually you can put an icon or a view with the methods setIcon or setCustomView
  7. create the classes eu/lucazanini/scrollingtab/ and eu/lucazanini/scrollingtab/

  8. launch the app

In the event onPause of the Fragment containing the ScrollView I save the value of the scrolled position of the ScrollView along the y-axis in the variable “yPos”, in the event onResume I restore the value of the variable “yPos” and I set the scrolled position of the ScrollView.
I must use the code

to execute the scroll, the only call to the method scrollTo(…) doesn’t work.
This example assumes that the Fragment is not destroyed between a call and the other and then, for example, the restoring of the position of the ScrollView is not executed if the user closes and restarts the main activity.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.