Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 456
Matthew Runo Avatar asked Dec 23 '11 19:12

Matthew Runo


3 Answers

Using of getFirstVisiblePosition() is good, but I've found a nice solution, just to save a state of view.

//state of view (includes scroll position) as a Parceble
Parcelable mobileGalleryState = gridView.onSaveInstanceState();

//just restore previous state including all changes are made before
gridView.onRestoreInstanceState(mobileGalleryState);

By the way, you can use it for ListView also.

like image 122
Dimon Avatar answered Oct 24 '22 05:10

Dimon


You can use the following method, it will work for all Android versions.

To save the current scrolling position:

int index = gridView.getFirstVisiblePosition();

Then after orientation change, use the following code to set the gridView position to the saved index:

gridView.setSelection(index);
like image 24
koder Avatar answered Oct 24 '22 07:10

koder


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!

like image 19
Dimitris Makris Avatar answered Oct 24 '22 06:10

Dimitris Makris