如何从AccessibilityNodeInfo中的所有子节点获取文本

时间:2018-05-30 18:49:22

标签: java android accessibilityservice android-accessibility accessibility-api

我正在尝试从AccessiblityNodeInfo的所有子节点读取文本。

我尝试了AccessiblityNodeInfo.getParent()AccessibilityNodeInfo.getChildCount()

for(int i=0; i<accessibilityNodeInfo.getChildCount();i++){
accessibilityNodeInfo.getChild(i).getText();
}

如上所述访问子节点以从子节点获取文本。但它没有提供屏幕上的所有文字。

任何人都可以建议我做什么来获取文字吗?

1 个答案:

答案 0 :(得分:0)

private List<CharSequence> getAllChildNodeText(AccessibilityNodeInfoCompat infoCompat) {
    List<CharSequence> contents = new ArrayList<>();
    if (infoCompat == null)
        return contents;
    if (infoCompat.getContentDescription() != null) {
        contents.add(infoCompat.getContentDescription().toString().isEmpty() ? "unlabelled" : infoCompat.getContentDescription());
    } else if (infoCompat.getText() != null) {
        contents.add(infoCompat.getText().toString().isEmpty() ? "unlabelled" : infoCompat.getText());
    } else {
        getTextInChildren(infoCompat, contents);
    }
    if (infoCompat.isClickable()) {
        if (infoCompat.getClassName().toString().contains(Button.class.getSimpleName())) {
            if (contents.size() == 0) {
                contents.add("Unlabelled button");
            } else {
                contents.add("button");
            }
        }
        contents.add("Double tap to activate");
    }
    return contents;
}


private void getTextInChildren(AccessibilityNodeInfoCompat nodeInfoCompat, List<CharSequence> contents) {
    if (nodeInfoCompat == null)
        return;
    if (!nodeInfoCompat.isScrollable()) {
        if (nodeInfoCompat.getContentDescription() != null) {
            contents.add(nodeInfoCompat.getContentDescription());
        } else if (nodeInfoCompat.getText() != null) {
            contents.add(nodeInfoCompat.getText());
        }
        if (nodeInfoCompat.getChildCount() > 0) {
            for (int i = 0; i < nodeInfoCompat.getChildCount(); i++) {
                if (nodeInfoCompat.getChild(i) != null) {
                    getTextInChildren(nodeInfoCompat.getChild(i), contents);
                }
            }
        }
    }
}