views:

614

answers:

2

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. :)

+2  A: 

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.

CommonsWare
Amazing answer! Thanks a lot.Related question: http://stackoverflow.com/questions/1091048/alternatives-to-window-scrollmaxy
alex
+2  A: 

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 * scrollRatio);
    webView.scrollTo(0, y);
  • Using a float and calculating a ratio works in the case of flipping between landscape and portrait.
  • May work well enough but not perfectly when mixed with autoresizing images.
  • Scale may also be taken into account. I tend to stash the scale in a preference in the onPause() method, and then webView.setInitialScale(scale) before you start loading the page.
  • I have found that setting the web view to invisible when scrollRatio > 0 looks better.
jamesh
Works nicely. And I confirm that the scale should be taken into account. Thanks.
Immortal