在层次结构中获取视图,我有这两个函数都可用。虽然 findViewById 更容易使用,但我经常看到建议说它可能是一项昂贵的操作,如果可能应该避免使用。
因此,是否使用 getChildAt 更快?在何时更好地使用哪个,有没有任何指南?
因此,是否使用 getChildAt 更快?在何时更好地使用哪个,有没有任何指南?
findViewById 和 getChildAt - 哪一个更快?
getChildAt
比 findViewById
快,因为它只是在指定的 index
(索引)上访问一个 View
数组。
那么,使用 getChildAt 会更快吗?
确实会更快,但您必须知道要查找的 View
的 index
。如果您没有任何机制来跟踪索引,那么您就必须查找它,然后回到 findViewById
。您可能最终会重新编写自己的版本的 findViewById
。我的建议是不要担心这个问题。
查看 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;
}