Maintain Scroll Position of GridView through Screen Rotation

a 夏天 提交于 2019-12-31 12:59:47

问题


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.


回答1:


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!




回答2:


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);



回答3:


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.



来源:https://stackoverflow.com/questions/8619794/maintain-scroll-position-of-gridview-through-screen-rotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!