findViewById 与 getChildAt - 哪个更快?

findViewById vs getChildAt - which one is quicker?

获取层次结构中的视图我可以使用这两个函数。虽然 findViewById 更易于使用,但我经常看到有人建议它可能是一项昂贵的操作,应尽可能避免。

因此,使用 getChildAt 会更快吗?是否有关于何时使用哪个更好的指南?

查看 ViewGroup 实现 findViewById 最终会遍历子项并比较 id,所以我建议只使用 findViewById 方法。

@Override
protected View findViewTraversal(@IdRes int id) {
    if (id == mID) {
        return this;
    }

    final View[] where = mChildren;
    final int len = mChildrenCount;

    for (int i = 0; i < len; i++) {
        View v = where[i];

        if ((v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) {
            v = v.findViewById(id);

            if (v != null) {
                return v;
            }
        }
    }

    return null;
}

findViewById vs getChildAt - which one is quicker?

getChildAt 确实比 findViewById 快,因为它只是访问指定 index 处的 View 数组。

Therefore, would it be any quicker to use getChildAt instead

确实会,但是您必须知道要查找的 Viewindex。如果您没有任何机制来跟踪索引,那么您必须寻找它,然后您又回到了 findViewById。您可能最终会重新编写自己的 findViewById 版本。我的两分钱,别担心。