Reputation: 57216
To put it simple: I want to bookmark the current position (probably several positions) in a html file displayed in a WebView to later restore it. Any little hint would help. :)
Upvotes: 7
Views: 8790
Reputation: 20111
The approach I took was as follows:
In the onSaveInstanceState()
method, calculate how far down the page the user had scrolled.
int contentHeight = webView.getContentHeight();
int scrollY = webView.getScrollY();
float scrollPercent = ((float) scrollY / ((float) contentHeight));
Stash that in the bundle. When restoring the page in the onCreate()
method, wait for the page to finish loading (in WebClient.onPageFinished()
), scroll to the recorded position:
int contentHeight = webView.getContentHeight();
int y = (int) ((float) contentHeight * scrollPercent);
webView.scrollTo(0, y);
float
and calculating a ratio works in the case of flipping between landscape and portrait.onPause()
method, and then webView.setInitialScale(scale)
before you start loading the page.scrollPercent > 0
looks better.Upvotes: 6
Reputation: 1007544
If by "the current position" you mean a point somewhere in a given page, I do not believe that is possible...at least not purely from Java. The whole WebKit API exposed to Java lacks much of anything that deals with the content of pages.
If you have control over the page content, and there's a way to know these positions via in-page Javascript, you could:
Step #1: Use WebView#addJavascriptInterface()
to add an object with some sort of recordPosition()
method, saving the information wherever is appropriate
Step #2: Create a Javascript function that calls recordPosition()
on the injected object.
and then either:
Step #3a: Trigger that Javascript function from Javascript itself (e.g., based on a click), or
Step #3b: Call loadUrl("javascript:...");
on your WebView
, where ...
is replaced by Javascript code to trigger the Javascript function from step #2.
Restoring these positions would have to work much the same way: have Javascript do the actual restores, possibly triggered by Java code.
Note that I have no idea if what you want (get/set the current position) is available from Javascript, as I'm not much of an in-browser coder.
Upvotes: 6