当前位置 : 主页 > 手机开发 > android >

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

来源:互联网 收集:自由互联 发布时间:2021-06-11
我需要获取所有活动组件的数组,然后我需要迭代这个数组并选择,例如,只选择按钮. 这该怎么做 ? 这可能对你有所帮助…… public ArrayListButton getButtons() { ArrayListButton buttons = new ArrayLis
我需要获取所有活动组件的数组,然后我需要迭代这个数组并选择,例如,只选择按钮.
这该怎么做 ? 这可能对你有所帮助……

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);
        }
    }
}
网友评论