Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android webview.scrollTo is not working

I'm calling to webview.scrollTo in onPageFinished function, but it doesn't do anything.

    public void onPageFinished(WebView view, String url) 
    {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
        webview.scrollTo(0, scrollY);
    }

Any idea why? How can I scroll a page automatically after it finished to load?

like image 850
RafaelJan Avatar asked Mar 29 '14 21:03

RafaelJan


1 Answers

It appears to me that there's a race condition between the completion of onPageFinished, onProgressChanged, WebView.scrollTo, and the display (actually drawing to the screen) of the web page.

After the page is displayed, the WebView 'thinks' it has scrolled to your scrollY position.

To test, you could verify that WebView.getScrollY() returns what you desire, but the display of the page is not in that position.

To work around this issue, here is a non-deterministic approach to scroll to Y immediately after the page is presented:

    ...
    webView = (WebView) view.findViewById(R.id.web_view_id);
    webView.loadData( htmlToDisplay, "text/html; charset=UTF-8", null);
    ...
    webView.setWebViewClient( new WebViewClient() 
    { ... } );
    webView.setWebChromeClient(new WebChromeClient() 
    {
        ...

        @Override
        public void onProgressChanged(WebView view, int progress) {
            ...
            if ( view.getProgress()==100) {
                // I save Y w/in Bundle so orientation changes [in addition to
                // initial loads] will reposition to last location
                jumpToY( savedYLocation );
            }
        }

     } );

    ...

  private void jumpToY ( int yLocation ) {
      webView.postDelayed( new Runnable () {
          @Override
          public void run() {
              webView.scrollTo(0, yLocation);
          }
      }, 300);
  }

The final parameter of 300 ms appears to allow the system to 'catchup' before the jumpToY is invoked. You might, depending upon platforms this runs on, play with that value.

Hope this helps

-Mike

like image 95
Magic Hands Pellegrin Avatar answered Oct 21 '22 06:10

Magic Hands Pellegrin