Android技术——在Android中的随意视图中找控件

1、在非常多情况下,我们可能不知道控件的id,可是我们却希望在包括这个控件的视图中找到它,能够採用例如以下做法:

例:在Activity的根视图中找出当中全部的Button控件

    private void findButton(ViewGroup group, List<Button> result)
    {
        if (group != null)
        {
            for (int i = 0, j = group.getChildCount(); i < j; i++)
            {
                View child = group.getChildAt(i);
                if (child instanceof Button)
                {
                    result.add((Button) child);
                } else if (child instanceof ViewGroup)
                {
                    findButton((ViewGroup) child, result);
                }
            }
        }
    }

在Activity中调用:

        List<Button> result = new ArrayList<Button>();
        this.findButton((ViewGroup) this.getWindow().getDecorView(), result);

这种方法事实上就是递归地从根视图開始查找整个控件树,终于找到符合要求的控件,稍加改写就能够满足各种找控件的需求。

原文地址:https://www.cnblogs.com/lxjshuju/p/6823347.html