Is there a listener for when the WebView displays it's content?

cottonBallPaws picture cottonBallPaws · Oct 31, 2010 · Viewed 36.2k times · Source

Using WebViewClient and/or the WebChromeClient you can get a listener for when the page has loaded, however this is sometimes called before the WebView has any content in it, before it has displayed anything.

What would be a efficient method for determining when the WebView has displayed it's content?

Edit: (Trying to be more clear)

When I load a page in a WebView, I want to set the scroll to a specific position. It seems that the scroll position cannot be set until the page is loaded and it has an actual content height. So, I have tried two different approaches to determining when the page has finished loading, onPageFinished() from the WebViewClient and also onProgressChanged() from the WebChromeClient. Both of these tell me when the page has finished loading.

However, the problem is that sometimes it is called before the page has been displayed and therefore the page has no height and the scroll call does nothing.

I am trying to find a solid way to determine when the page is ready to be scrolled, ie. when it has its content height.

I imagine I could setup a checking loop after it finished loading to keep looking for when the height is available but that seemed like quite the hack. Hoping there is a cleaner way.

Answer

cottonBallPaws picture cottonBallPaws · Feb 4, 2013

I successfully used Richard's answer with a PictureListener for a few years, but I no longer recommend this as the best solution.

This is for two reasons:

  1. webView.setPictureListener and PictureListener are both deprecated.
  2. Using this listener will cause the WebView to allocate a new Picture often. This allocation is expensive and this can have some significant performance impacts or even cause native crashes on JellyBean MR1.

Instead I recommend creating a subclass of WebView and overriding invalidate() like so:

@Override
public void invalidate() {
    super.invalidate();

    if (getContentHeight() > 0) {
        // WebView has displayed some content and is scrollable.
    }
}

If you still want to use the PictureListener method, you will get better performance if you setPictureListener back to null after you are done with it.