在android中查找webview中特定文本的数量

时间:2015-04-14 11:28:43

标签: android webview

我需要在webview中找到特定的文本,但我无法做到。 在api级别16之后不推荐使用findall,我们需要使用findAllAsync。 我们也可以使用WebView.FindListener。 早些时候,我使用findall,它工作正常,但它不适用于kitkat和棒棒糖。我尝试过findAllAsync,但我无法找到任何特定文本的计数。 我的代码在这里:

@Override
public void onFindResultReceived(int activeMatchOrdinal,
        int numberOfMatches, boolean isDoneCounting) {
    if (isDoneCounting) {
        updateMatchCount(activeMatchOrdinal, numberOfMatches,
                numberOfMatches == 0);

    }
    Log.e("test", "data ::" + numberOfMatches);

}

public void findAll() {
    if (webviewdevelopment == null) {
        throw new AssertionError(
                "No WebView for FindActionModeCallback::findAll");
    }
    CharSequence find = "Following";
    if (0 == find.length()) {
        webviewdevelopment.clearMatches();
        mMatchesFound = false;
        webviewdevelopment.findAll(null);
    } else {
        mMatchesFound = true;
        mNumberOfMatches = 0;
        webviewdevelopment.findAllAsync(find.toString());

    }

    Log.e("test", "data ::" + mNumberOfMatches);

}

public void updateMatchCount(int matchIndex, int matchCount,
        boolean isEmptyFind) {
    if (!isEmptyFind) {
        mNumberOfMatches = matchCount;
        mActiveMatchIndex = matchIndex;
        updateMatchesString();
    } else {

        mNumberOfMatches = 0;
    }
}

private void updateMatchesString() {
    if (mNumberOfMatches == 0) {

    } else {

        Log.e("test", "data ::" + mNumberOfMatches + ","
                + mActiveMatchIndex + 1 + "," + mNumberOfMatches);

    }

}

private void findNext(boolean next) {
    if (webviewdevelopment == null) {
        throw new AssertionError(
                "No WebView for FindActionModeCallback::findNext");
    }
    if (!mMatchesFound) {
        findAll();
        return;
    }
    if (0 == mNumberOfMatches) {
        // There are no matches, so moving to the next match will not do
        // anything.
        return;
    }
    webviewdevelopment.findNext(next);
    updateMatchesString();
}

@Override
public void onFindResultReceived(int activeMatchOrdinal,
        int numberOfMatches, boolean isDoneCounting) {
    if (isDoneCounting) {
        updateMatchCount(activeMatchOrdinal, numberOfMatches,
                numberOfMatches == 0);

    }
    Log.e("test", "data ::" + numberOfMatches);

}

任何人有任何演示请提供给我,谢谢

1 个答案:

答案 0 :(得分:5)

在代码中使用它来搜索所需的字符串。

webview.findAllAsync("Your String");

将FindListener添加到WebView

webview.setFindListener(new FindListener() {

    @Override
    public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
        Toast.makeText(getApplicationContext(), "Matches: " + numberOfMatches, Toast.LENGTH_LONG).show();
    }
});