'In Android, how to get the index of the AccessibilityNodeInfo in its parental node

I want to find the index of the AccessibilityNodeInfo in its parental node. For example, if the classname of the current node is LinearLayout and the classname of its parental node is FrameLayout, and there are multiple LinearLayout under the FrameLayout, I want to know the index of this LinearLayout-whether it's the first LinearLayout, the second LinearLayout or the third LinearLayout and so on.

Thank you



Solution 1:[1]

It seems that there is no built-in function that can meet my requirement, so I wrote a function. The idea is simple, get all the children of an AccessibilityNodeInfo. Then compare the classname with your intended classname. Finally use bounds to decide the index.

     public int getNodeIndex(AccessibilityNodeInfo nodeInfo){
        if (nodeInfo.getParent()!=null) {
            AccessibilityNodeInfo parentalNode=nodeInfo.getParent();
            int childCount = parentalNode.getChildCount();
            if (childCount>1){
                List<Rect> rects=new ArrayList<>();
                for (int i=0;i<childCount;i++){
                    Rect rect = new Rect();
                    if (parentalNode.getChild(i).getClassName().equals(nodeInfo.getClassName())) {
                        parentalNode.getChild(i).getBoundsInScreen(rect);
                        rects.add(rect);

                    }
                }
                Rect nodeRect=new Rect();
                nodeInfo.getBoundsInScreen(nodeRect);
                int i=0;
                int indexNode=0;
                while (i<rects.size()){
                    if (nodeRect.equals(rects.get(i))){
                        indexNode=i;
                        break;
                    }
                    i++;
                }
            }
            else{
                return 0;
            }
        }
        return 0;
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ziyao