【Android源码】View的创建流程

通过上篇的LayoutInflater 分析,我们知道了LayoutInflater服务的注册流程,最终是通过PhoneLayoutInflater对象的onCreateView来创建对应的View对象的。那么具体的View的创建过程是怎么样的呢,今天我们来一起分析一下。

通常情况下,一个Activity的界面的创建是通过setContentView来引入布局。

mWindow = new PhoneWindow(this, window);

public void setContentView(@LayoutRes int layoutResID) {
   getWindow().setContentView(layoutResID);
   initWindowDecorActionBar();
}

而Activity的setContentView方法是通过调用Window的setContentView方法,而Window是一个抽象对象,它的具体实现类就是PhoneWindow。在PhoneWindow中找到setContentView方法:

@Override
public void setContentView(int layoutResID) {
     // 如果mContentParent为空时先构建
   if (mContentParent == null) {
       installDecor();
   } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
       mContentParent.removeAllViews();
   }

   if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
       final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
               getContext());
       transitionTo(newScene);
   } else {
            // 通过LayoutInflater解析布局
       mLayoutInflater.inflate(layoutResID, mContentParent);
   }
   mContentParent.requestApplyInsets();
   final Callback cb = getCallback();
   if (cb != null && !isDestroyed()) {
       cb.onContentChanged();
   }
}

可以发现,setContentView也是通过LayoutInflater加载布局加载到mContentParent中。我们再看inflate方法:

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
   return inflate(resource, root, root != null);
}

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
   final Resources res = getContext().getResources();
   if (DEBUG) {
       Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
               + Integer.toHexString(resource) + ")");
   }

   final XmlResourceParser parser = res.getLayout(resource);
   try {
       return inflate(parser, root, attachToRoot);
   } finally {
       parser.close();
   }
}

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
   synchronized (mConstructorArgs) {
       Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

       final Context inflaterContext = mContext;
       final AttributeSet attrs = Xml.asAttributeSet(parser);
       // Context对象
       Context lastContext = (Context) mConstructorArgs[0];
       mConstructorArgs[0] = inflaterContext;
       // 父视图
       View result = root;

       try {
           // Look for the root node.
           int type;
           // 找到root元素
           while ((type = parser.next()) != XmlPullParser.START_TAG &&
                   type != XmlPullParser.END_DOCUMENT) {
               // Empty
           }

           if (type != XmlPullParser.START_TAG) {
               throw new InflateException(parser.getPositionDescription()
                       + ": No start tag found!");
           }

           final String name = parser.getName();
           
                // 解析merge标签
           if (TAG_MERGE.equals(name)) {
                    // 如果是merge标签调用新方法,将merge标签内的元素全部加载到父视图中
               rInflate(parser, root, inflaterContext, attrs, false);
           } else {
                // 通过xml的tag来解析根视图
                final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                // 不是merge标签,直接解析布局中的视图
               ViewGroup.LayoutParams params = null;

               if (root != null) {
                   // 生成布局参数
                   params = root.generateLayoutParams(attrs);
                   if (!attachToRoot) {
                       temp.setLayoutParams(params);
                   }
               }
               // Inflate all children under temp against its context.
               // 解析temp视图下的所有view
               rInflateChildren(parser, temp, attrs, true);

               // 如果root不为空并且attachToRoot为true,将temp加入到父视图中
               if (root != null && attachToRoot) {
                   root.addView(temp, params);
               }
               // 如果root为空 或者 attachToRoot为false,返回的结果就是temp
               if (root == null || !attachToRoot) {
                   result = temp;
               }
           }

       } catch (XmlPullParserException e) {
           throw ie;
       } catch (Exception e) {
           throw ie;
       } finally {
           // Don't retain static reference on context.
           mConstructorArgs[0] = lastContext;
           mConstructorArgs[1] = null;

           Trace.traceEnd(Trace.TRACE_TAG_VIEW);
       }

       return result;
   }
}

最终调用public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)方法,其中第一个参数是xml解析器,第二个参数是要解析布局的父视图,第三个参数标识是否需要加入到父视图中。

上面的inflate方法所做的操作主要有以下几步:

  1. 解析xml的根标签
  2. 如果根标签是merge,那么调用rInflate解析,将merge标签下的所有子View直接添加到根标签中
  3. 如果不是merge,调用createViewFromTag解析该元素
  4. 调用rInflate解析temp中的子View,并将这些子View添加到temp中
  5. 通过attachToRoot,返回对应解析的根视图

我们先看createViewFromTag方法:

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
       boolean ignoreThemeAttr) {

   try {
       View view;

       if (view == null) {
           final Object lastContext = mConstructorArgs[0];
           mConstructorArgs[0] = context;
           try {
                // 通过.来判断是自定义View还是内置View
               if (-1 == name.indexOf('.')) {
                   view = onCreateView(parent, name, attrs);
               } else {
                   view = createView(name, null, attrs);
               }
           } finally {
               mConstructorArgs[0] = lastContext;
           }
       }

       return view;
   } catch (InflateException e) {
       throw e;

   } catch (ClassNotFoundException e) {
       throw ie;
   }
}

我们可以发现,解析View的时候是通过.来判断是内置的View还是自定义的View的,那么我们就能知道为什么在写布局文件中自定义的View需要完整路径了。

在解析内置View的时候就是通过类似于PhoneLayoutInflater的onCreateView的解析方式,通过在name前加上android.view.最终也是调用createView来解析。

而自定义view则是在调用createView(name, null, attrs)时,第二个参数的前缀传递null。

public final View createView(String name, String prefix, AttributeSet attrs)
       throws ClassNotFoundException, InflateException {
   // 从缓存中获取view的构造函数
   Constructor<? extends View> constructor = sConstructorMap.get(name);
   if (constructor != null && !verifyClassLoader(constructor)) {
       constructor = null;
       sConstructorMap.remove(name);
   }
   Class<? extends View> clazz = null;

   try {
       Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
            // 如果没有缓存
       if (constructor == null) {
           // 如果前缀不为空构造完整的View路径并加载该类
           clazz = mContext.getClassLoader().loadClass(
                   prefix != null ? (prefix + name) : name).asSubclass(View.class);
           // 获取该类的构造函数
           constructor = clazz.getConstructor(mConstructorSignature);
           constructor.setAccessible(true);
           // 将构造函数加入缓存中
           sConstructorMap.put(name, constructor);
       } else {
       }

       Object[] args = mConstructorArgs;
       args[1] = attrs;
            // 通过反射构建View
       final View view = constructor.newInstance(args);
       if (view instanceof ViewStub) {
           // Use the same context when inflating ViewStub later.
           final ViewStub viewStub = (ViewStub) view;
           viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
       }
       return view;

   }
}

createView相对简单,通过判断前缀,来构建View的完整路径,并将该类加载到虚拟机中,获取构造函数并缓存,再通过构造函数创建该View对象,并返回。这个时候我们就获得了根视图。接着调用rInflateChildren方法解析子View,并最终调用rInflate方法:

void rInflate(XmlPullParser parser, View parent, Context context,
       AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {

    // 获取树的深度,通过深度优先遍历
   final int depth = parser.getDepth();
   int type;

   while (((type = parser.next()) != XmlPullParser.END_TAG ||
           parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {

       if (type != XmlPullParser.START_TAG) {
           continue;
       }

       final String name = parser.getName();
       
       if (TAG_REQUEST_FOCUS.equals(name)) {
           parseRequestFocus(parser, parent);
       } else if (TAG_TAG.equals(name)) {// 解析tag标签
           parseViewTag(parser, parent, attrs);
       } else if (TAG_INCLUDE.equals(name)) {// 解析include标签
           if (parser.getDepth() == 0) {
               throw new InflateException("<include /> cannot be the root element");
           }
           parseInclude(parser, context, parent, attrs);
       } else if (TAG_MERGE.equals(name)) {// 解析到merge标签,并报错
           throw new InflateException("<merge /> must be the root element");
       } else {
            // 解析到普通的子View,并调用createViewFromTag获得View对象
           final View view = createViewFromTag(parent, name, context, attrs);
           final ViewGroup viewGroup = (ViewGroup) parent;
           final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
           // 递归解析
           rInflateChildren(parser, view, attrs, true);
           // 将View加入到父视图中
           viewGroup.addView(view, params);
       }
   }

   if (finishInflate) {
       parent.onFinishInflate();
   }
}

rInflate方法通过深度优先遍历的方式来构造视图树,当解析到一个View的时候就再次调用rInflate方法,直到将路径下的最后一个元素,并最终将View加入到父视图中。

这就是完整的View的创建流程。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,881评论 4 368
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,052评论 1 301
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,598评论 0 250
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,407评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,823评论 3 294
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,872评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,037评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,778评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,505评论 1 247
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,745评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,233评论 1 264
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,568评论 3 260
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,231评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,141评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,939评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,954评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,784评论 2 275

推荐阅读更多精彩内容