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.
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.
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);
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With