To save and restore the scroll position of a ScrollView when the phone orientation changes you can do the following:
Save the current position in the onSaveInstanceState method:
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putIntArray("ARTICLE_SCROLL_POSITION",
new int[]{ mScrollView.getScrollX(), mScrollView.getScrollY()});
}
Then restore the position in the onRestoreInstanceState method, note that we need to post a runnable to the ScrollView to get this to work:
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
final int[] position = savedInstanceState.getIntArray("ARTICLE_SCROLL_POSITION");
if(position != null)
mScrollView.post(new Runnable() {
public void run() {
mScrollView.scrollTo(position[0], position[1]);
}
});
}
Advertisement
It made my work simple. I just copy-pasted, work complete.
Thanks for the simple and useful post.