findViewById和getChildAt哪个更快?(涉及IT技术)

3
在层次结构中获取视图,我有这两个函数都可用。虽然 findViewById 更容易使用,但我经常看到建议说它可能是一项昂贵的操作,如果可能应该避免使用。
因此,是否使用 getChildAt 更快?在何时更好地使用哪个,有没有任何指南?

我经常看到建议,但会忽略它们。 - pskink
我猜findViewById()更快,只需访问具有ID的特定视图。更容易实现。 - Onkar Nene
2个回答

3

findViewById 和 getChildAt - 哪一个更快?

getChildAtfindViewById 快,因为它只是在指定的 index (索引)上访问一个 View 数组。

那么,使用 getChildAt 会更快吗?

确实会更快,但您必须知道要查找的 Viewindex。如果您没有任何机制来跟踪索引,那么您就必须查找它,然后回到 findViewById。您可能最终会重新编写自己的版本的 findViewById。我的建议是不要担心这个问题。


1

查看 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;
}

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