[关闭]
@act262 2017-05-24T14:26:19.000000Z 字数 942 阅读 1154

findViewById 源码分析

AndroidSource


在Activity中调用的findViewById方法分析具体流程如下:

Activity中封装的方法

  1. public View findViewById(@IdRes int id) {
  2. return getWindow().findViewById(id);
  3. }

也就是调用到Window的findViewById方法

  1. public View findViewById(@IdRes int id) {
  2. return getDecorView().findViewById(id);
  3. }
  4. public abstract View getDecorView();

调用到View的findViewById,再调用findViewTraversal这个遍历方法

  1. public final View findViewById(@IdRes int id) {
  2. if (id < 0) {
  3. return null;
  4. }
  5. return findViewTraversal(id);
  6. }
  7. // 遍历查找,由子类覆盖实现
  8. protected View findViewTraversal(@IdRes int id) {
  9. if (id == mID) {
  10. return this;
  11. }
  12. return null;
  13. }

这里的getDecorView具体实现类是DecorView,继承自FrameLayoutFrameLayout中没有复写findViewTraversal,其实现是在ViewGroup的findViewTraversal实现的。

  1. protected View findViewTraversal(@IdRes int id) {
  2. if (id == mID) {
  3. return this;
  4. }
  5. final View[] where = mChildren;
  6. final int len = mChildrenCount;
  7. // 遍历其子View来查找匹配Id的View
  8. for (int i = 0; i < len; i++) {
  9. View v = where[i];
  10. // 这个View不属于root
  11. if ((v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) {
  12. v = v.findViewById(id);
  13. // 找到了返回
  14. if (v != null) {
  15. return v;
  16. }
  17. }
  18. }
  19. return null;
  20. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注