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]); } }); }
It made my work simple. I just copy-pasted, work complete.
Thanks for the simple and useful post.
if I copy & paste it, I become a warning: mScrollView cannot be resolved
Plz help me, I’m just a beginner.
My code:
public class HadisiActivity extends Activity {
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putIntArray(“ARTICLE_SCROLL_POSITION”,
new int[]{ mScrollView.getScrollX(), mScrollView.getScrollY()});
}
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]);
}
});
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hadisi_layout);
}
…
great… 🙂
Thanks, it worked great
How did you know that scrollTo had to be called from within a Runnable?
Thank’s this code works fine 😀 great post!
[…] Please take a look at: https://eliasbland.wordpress.com/2011/07/28/how-to-save-the-position-of-a-scrollview-when-the-orienta… […]