0

I want once the page automatically scroll WebView to one of my titles in Html with id = "my_header" in the upper left corner. How to do it when my Fragment is loaded?

WebView myWebView = (WebView) v.findViewById(R.id.web_view);
myWebView.setWebViewClient(new WebViewClient());
myWebView.getSettings().setSupportZoom(true);
myWebView.getSettings().setUseWideViewPort(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.loadUrl(resource);
user3815165
  • 258
  • 2
  • 16
  • 1
    Typically, if you want to scroll to an `id` you can append `#my_header` to the end of the url. Try that, see if it works. For example: http://stackoverflow.com/questions/25990208/scroll-webview-dynamically#post-editor – musefan Sep 23 '14 at 08:52

1 Answers1

0

If you just want to scroll down to an element and you have access to the page that you are loading, in javascript, you could do something like this on page load:

var container = $('div'),
    scrollTo = $('#my_header');

container.scrollTop(
    scrollTo.offset().top - container.offset().top + container.scrollTop()
);

See this question: How to scroll to specific item using jQuery?

If you do not wish to modify the underlying resource then you can add the following Java code to your WebView, which will call the above javascript code, once the page is loaded:

WebView myWebView = (WebView)v.findViewById(R.id.web_view);
myWebView.getSettings().setSupportZoom(true);
myWebView.getSettings().setUseWideViewPort(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebChromeClient(new WebChromeClient());
myWebView.setWebViewClient(new WebViewClient() {

    @Override
    public void onPageFinished(WebView view, String url) {
      String javascript = "javascript:"
          + "var container = $('div'),scrollTo = $('#my_header');"
          + "container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop());";
      view.loadUrl(javascript);
    }
});

// Finally, load the page
myWebView.loadUrl(resource);

Note that this will run the javascript whenever any page is loaded by that WebViewClient. You could easily add logic to only call the javascript scroll code for a specific page, if needed though.

Community
  • 1
  • 1
Dylan Watson
  • 2,283
  • 2
  • 20
  • 38
  • This isn't a javascript question... and if the solution is to run some javascript then you should include how to inject/run the javascript using a `WebView` as per the question – musefan Sep 23 '14 at 08:50
  • My assumption was that they would have access to modify the page (I.e Add javascript to it). I have updated my answer, indicating how to run javascript on any page, once it has loaded. – Dylan Watson Sep 23 '14 at 09:22