Maintain WebView content scroll position on orientation change
<p>The browsers in Android 2.3+ do a good job at maintaining the scrolled position of content on an orientation changed. </p>

<p>I'm trying to achieve the same thing for a WebView which I display within an activity but without success.</p>

<p>I've tested the manifest change (android:configChanges="orientation|keyboardHidden") to avoid activity recreation on a rotation however because of the different aspect ratios the scroll position does not get set to where I want. Furthermore this is <strong>not</strong> a solution for me as I need to have different layouts in portrait and landscape.</p>

<p>I've tried saving the WebView state and restoring it but this resuls in the content being displayed at the top again. </p>

<p>Furthermore attempting to scroll in <code>onPageFinished</code> using <code>scrollTo</code> doesn't work even though the height of the WebView is non-zero at this point.</p>

<p>Any ideas? Thanks in advance. Peter.</p>

<p><strong>Partial Solution:</strong></p>

<p>My colleague managed to get scrolling working via a javascript solution. For simple scrolling to the same vertical position, the WebView's 'Y' scroll position is saved in <code>onSaveInstanceState</code> state. The following is then added to <code>onPageFinished</code>:</p>

<pre><code>public void onPageFinished(final WebView view, final String url) {
    if (mScrollY &gt; 0) {
        final StringBuilder sb = new StringBuilder("javascript:window.scrollTo(0, ");
        sb.append(mScrollY);
        sb.append("/ window.devicePixelRatio);");
        view.loadUrl(sb.toString());
    }
    super.onPageFinished(view, url);
}
</code></pre>

<p>You do get the slight flicker as the content jumps from the beginning to the new scroll position but it is barely noticeable. The next step is try a percentage based method (based on differences in height) and also investigate having the WebView save and restore its state.</p>
