android webview.scrollTo is not working

后端 未结 1 916
感情败类
感情败类 2021-01-05 17:51

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

    public void onPageFinished(WebView view, String url) 
    {
            


        
相关标签:
1条回答
  • 2021-01-05 18:33

    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

    0 讨论(0)
提交回复
热议问题