我想搜索一个网页,找到两个字符串。我使用这段代码:
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
webView.findAllAsync("str1");
webView.findAllAsync("str2");
}
});
和这个FindListener:
public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
if(numberOfMatches > 0)
(...) //do something
}
但在这种情况下,仅为 str2 调用onFindResultReceived
,如果 str1 的numberOfMatches
大于0,则不执行任何操作。是什么原因,我该怎么做才能解决问题?
答案 0 :(得分:0)
来自the docs
在页面上查找find的所有实例并异步突出显示它们。通知任何已注册的WebView.FindListener。对此的连续调用将取消任何待处理的搜索。
换句话说,你的第二个电话会取消第一个电话。解决方案是等待每次搜索完成以开始下一次搜索。下面是一个可以为任意数量的字符串实现所需结果的示例
private int mCurrentSearchIndex = -1;
private String mSearchTerms = { "str1", "str2" }
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
nextSearch();
}
});
private void nextSearch() {
mCurrentSearchIndex ++; //the fisrt tiem this is called the index gets set to 0
if (mCurrentSearchIndex < mSearchTerms.length) {
//get the search string corresponding to this index and then search it
webView.findAllAsync(mSearchTerms[mCurrentSearchIndex]);
}
}
public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
if (isDoneCounting) {
if (numberOfMatches > 0) {
...
}
//here we know the previous find finished, so its safe to start another
nextSearch();
}
}