问题
I'm developing an application for serious of books by using Webview with local html files.
I want to allow the user to return to the last location that he read with the same font size that he choose.
- Font size - I'm using getScale to store the choosing scaling when the user close the App, and when the user open the App I'm loading it by using the setInitialScale with the stored scaling. It works good.
- Location - I'm using getScrollY to store scrolling when the user close the App, and when the user open the App I'm loading it by using the scrollTo with the stored scrolling. It works good.
The problem is when I'm using both. The font size loaded correctly, but the scrolling is not happen and I see the top of the html file. I tried to put setInitialScale and scrollTo in different locations in the code but nothing solve the issue.
Any idea how can I implement it?
Maybe webview has any method that allow doing it in other way?
回答1:
You're probably running into some sort of race - you can't call scrollTo
before the WebView has finished loading and has had a layout pass.
One approach would be to override WebView.onSizeChanged
and wait for the WebView to resize to the 'right' height before scrolling:
@Override
void onSizeChanged(int w, int h, int ow, int oh) {
super.onSizeChanged(w, h, ow, oh);
if (h >= savedScrollOffset)
scrollBy(0, savedScrollOffset);
}
Another option, if you control the HTML and use JavaScript, would be to save and restore the scroll offset using JavaScript. You could use LocalStorage to save the scroll offset and then restore it from LocalStorage when the page is loaded.
来源:https://stackoverflow.com/questions/21040065/webview-setinitialscale-prevent-scrollto-to-scroll-the-webview