Save the position of scrollview when the orientation changes

user1945196 picture user1945196 · Mar 23, 2015 · Viewed 16.1k times · Source

These is my layout:

detail layout

I need to save the scrolling position when the orientation changes. for example if the screen shows layout starting from middle name in portrait mode,it should start from same in the landscape mode.

Answer

Just set android:id on your scrolling element. Your view will save its scrolling position automatically.

Code from View.java:15554

protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
    if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
        mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
        Parcelable state = onSaveInstanceState();
        if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
            throw new IllegalStateException(
                    "Derived class did not call super.onSaveInstanceState()");
        }
        if (state != null) {
            // Log.i("View", "Freezing #" + Integer.toHexString(mID)
            // + ": " + state);
            container.put(mID, state);
        }
    }
}