WebView 显示其内容时是否有侦听器? [英] Is there a listener for when the WebView displays it's content?

查看:19
本文介绍了WebView 显示其内容时是否有侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 WebViewClient 和/或 WebChromeClient,您可以获得页面加载时的侦听器,但有时会在 WebView 中包含任何内容之前,在显示任何内容之前调用它.

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.

确定 WebView 何时显示其内容的有效方法是什么?

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

(试图更清楚)

当我在 WebView 中加载页面时,我想将滚动设置为特定位置.似乎在页面加载并具有实际内容高度之前无法设置滚动位置.因此,我尝试了两种不同的方法来确定页面何时完成加载,来自 WebViewClient 的 onPageFinished() 和来自 WebChromeClient 的 onProgressChanged().这两者都会告诉我页面何时完成加载.

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.

推荐答案

我成功地将 Richard's answer with a PictureListener 用于几年,但我不再推荐这是最好的解决方案.

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

这有两个原因:

  1. webView.setPictureListenerPictureListener 均已弃用.
  2. 使用这个监听器会导致 WebView 经常分配一个新的图片.这种分配代价高昂,而且可能会对性能产生一些重大影响,甚至会导致 JellyBean MR1 上的本机崩溃.

相反,我建议创建一个 WebView 的子类并像这样覆盖 invalidate():

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.
    }
}

如果您还想使用PictureListener 方法,则在完成后将PictureListener 设置回null 将获得更好的性能.

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.

这篇关于WebView 显示其内容时是否有侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆