如何在Android中遍历所有活动组件(视图)

3
我需要获取所有活动组件的数组,然后需要遍历该数组并选择,例如,只有按钮。如何做到这一点?
1个回答

9

这可能对您有所帮助...

public ArrayList<Button> getButtons() {
    ArrayList<Button> buttons = new ArrayList<Button>();
    ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView();
    findButtons(viewGroup, buttons);
    return buttons;
}

private static void findButtons(ViewGroup viewGroup,ArrayList<Button> buttons) {
    for (int i = 0, N = viewGroup.getChildCount(); i < N; i++) {
        View child = viewGroup.getChildAt(i);
        if (child instanceof ViewGroup) {
            findButtons((ViewGroup) child, buttons);
        } else if (child instanceof Button) {
            buttons.add((Button) child);
        }
    }
}

这篇帖子也许会有所帮助:https://dev59.com/Ym855IYBdhLWcg3wMBPV - Doc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接