Search code examples
androidgridvieworientation

Maintain Scroll Position of GridView through Screen Rotation


How can I maintain the scroll position of a GridView (it's filled with search results) throughout a screen reorientation?

I have the GridView inside a Fragment, and when I rotate the screen it jumps back up to the top of the list.

To make it even more tricky, in landscape mode my GridView has 3 columns.. in portrait mode it has 2 columns.

I can't seem to figure out how to keep the fragment's GridView scrolled to anywhere near where it should be when the screen orientation changes.


Solution

  • You can try this:

    Initially you have to get the current scrolling position of the GridView by calling:

    int index = gridview.getFirstVisiblePosition();
    

    Then you have to save this value while orientation changes and when the GridView is created again you have to move your gridview to this index.

    I suppose this could work:

    gridview.smoothScrollToPosition(int index)
    

    Hope this helps!