Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

java - onPageFinished not firing correctly when rendering web page

For some reason the onPageFinished is firing before the WebView has finished loading - I can't figure out why...

public class WebViewClientTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final WebView webview = (WebView) findViewById(R.id.webview);

    webview.setWebViewClient(new WebViewClient() {  
        @Override  
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(webview, url);
            webview.scrollTo(0, 500);
        }  
    });
    webview.loadUrl("http://www.google.co.uk/search?sourceid=chrome&ie=UTF-8&q=lala");

}
}

OK, well it looks like this isn't fixed. I think there's a race condition going on when loading the page, but can't get a reproducible behaviour.

I'm storing the HTML content of a webpage in a SQLite database for viewing when offline. I reload the content into the WebView with:

webView.loadDataWithBaseURL("fake://fake.com/", htmlBody, "text/html", "utf-8", null);

It seems that sometimes when the WebView loads it fires the WebViewClient.onPageFinished() method correctly, and other times it does not. Sometimes it appears to fire before the page has finished loading, producing a contentHeight of 0 and ignoring any scrollTo calls.

Anyone have any experience with this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had a project that had code which needed to run only after the webview had displayed it's content, and like you, onPageFinished() wasn't working. It fired too quickly, before the webview had actually rendered the page.

Instead, I had to use a "PictureListener" which gets fired when the webview actually updates the screen.

You use it like so:

mWebView.setPictureListener(new MyPictureListener());
//... and then later on....
class MyPictureListener implements PictureListener {

    @Override
    public void onNewPicture(WebView view, Picture arg1) {
      // put code here that needs to run when the page has finished loading and
      // a new "picture" is on the webview.      
    }    
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...