Android setContentView()\LayoutInflater\View 源码原理分析

版权声明:本文为博主csdn_aiyang原创文章,未经博主允许不得转载。 https://blog.csdn.net/csdn_aiyang/article/details/86626748

前言

通常情况下,我们创建一个Activity时,会通过setContentView来引入布局,将界面视图展现给用户看见。那么,为什么通过setContentView()就能将xml格式的布局文件加载到界面中呢?

 @Override
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 }

一、Activity中的setContentView()

1、当前activity是继承Activity时

SetContentView方法的源码如下:

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

调用了Window的setContentView方法。而Window是一个抽象对象,它的具体实现类就是PhoneWindow。PhoneWindow中的setContentView方法实现如下:

@Override
public void setContentView(int layoutResID) {

   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 {

       mLayoutInflater.inflate(layoutResID, mContentParent);//解析布局
   }
   mContentParent.requestApplyInsets();
   final Callback cb = getCallback();
   if (cb != null && !isDestroyed()) {
       cb.onContentChanged();
   }
}

2、当前activity继承AppCompatActivity

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        getDelegate().setContentView(layoutResID);
    }

    @Override
    public void setContentView(View view) {
        getDelegate().setContentView(view);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate().setContentView(view, params);
    }

实际上是通过调用getDelegate().setContentView()。getDelegate()源码实现如下:

 public AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, this);
        }
        return mDelegate;
}

AppCompatDelegate.create()源码:

 private static AppCompatDelegate create(Context context, Window window,
            AppCompatCallback callback) {
        final int sdk = Build.VERSION.SDK_INT;
        if (BuildCompat.isAtLeastN()) {
            return new AppCompatDelegateImplN(context, window, callback);
        } else if (sdk >= 23) {
            return new AppCompatDelegateImplV23(context, window, callback);
        } else if (sdk >= 14) {
            return new AppCompatDelegateImplV14(context, window, callback);
        } else if (sdk >= 11) {
            return new AppCompatDelegateImplV11(context, window, callback);
        } else {
            return new AppCompatDelegateImplV9(context, window, callback);
        }
    }

以上AppCompatdelegateImple * 都是继承 AppCompatDelegateImplBase

abstract class AppCompatDelegateImplBase extends AppCompatDelegate

AppCompatDelegate是个抽象类,里面定义了很多activity 的抽象方法,如下:

 <p>When using an {@link AppCompatDelegate}, you should call the following methods instead of the
* {@link android.app.Activity} method of the same name:</p>
* <ul>
*     <li>{@link #addContentView(android.view.View, android.view.ViewGroup.LayoutParams)}</li>
*     <li>{@link #setContentView(int)}</li>
*     <li>{@link #setContentView(android.view.View)}</li>
*     <li>{@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}</li>
*     <li>{@link #requestWindowFeature(int)}</li>
*     <li>{@link #hasWindowFeature(int)}</li>
*     <li>{@link #invalidateOptionsMenu()}</li>
*     <li>{@link #startSupportActionMode(android.support.v7.view.ActionMode.Callback)}</li>
*     <li>{@link #setSupportActionBar(android.support.v7.widget.Toolbar)}</li>
*     <li>{@link #getSupportActionBar()}</li>
*     <li>{@link #getMenuInflater()}</li>
*     <li>{@link #findViewById(int)}</li>
* </ul>
*
* <p>The following methods should be called from the {@link android.app.Activity} method of the
* same name:</p>
* <ul>
*     <li>{@link #onCreate(android.os.Bundle)}</li>
*     <li>{@link #onPostCreate(android.os.Bundle)}</li>
*     <li>{@link #onConfigurationChanged(android.content.res.Configuration)}</li>
*     <li>{@link #onStart()}</li>
*     <li>{@link #onStop()}</li>
*     <li>{@link #onPostResume()}</li>
*     <li>{@link #onSaveInstanceState(Bundle)}</li>
*     <li>{@link #setTitle(CharSequence)}</li>
*     <li>{@link #onStop()}</li>
*     <li>{@link #onDestroy()}</li>
* </ul>

其中,setContentView 的实现代码如下:

二、LayoutInflater.inflate() 

inflater.inflate(layoutId, null);
inflater.inflate(layoutId, root,false);
inflater.inflate(layoutId, root,true);

上面的setContentView是通过 LayoutInflater.inflate() 将布局加载到mContentParent中。inflate()方法实现如下:

inflater.inflate(layoutId, null) 方法里调用了inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot), 在该方法又调用了 inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) 。

/**
 * parser xml解析器
 * root  父容器
 * attackToRoot 是否加入到父容器中
 */
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
   synchronized (mConstructorArgs) {

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

       try {
           int type;
           // 找到root元素
           while ((type = parser.next()) != XmlPullParser.START_TAG &&
                   type != XmlPullParser.END_DOCUMENT) {
           }
           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);
                   }
               }
               // 解析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 (Exception e) {
           throw ie;
       } finally {
           mConstructorArgs[0] = lastContext;
           mConstructorArgs[1] = null;
       }
       return result;
   }
}

上面的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的创建流程

1、上面代码片段可见,解析View的时候是通过“.”来判断是内置的View还是自定义的View的。所以,在写布局文件中使用自定义的View需要完整路径。可以参考LayoutInflater通过PhoneLayoutInflater创建出来的onCreateView()。

PhoneLayoutInflater类:

public class PhoneLayoutInflater extends LayoutInflater {
    private static final String[] sClassPrefixList = {
        "android.widget.",
        "android.webkit.",
        "android.app."
    };
    public PhoneLayoutInflater(Context context) {
        super(context);
    }

    protected PhoneLayoutInflater(LayoutInflater original, Context newContext) {
        super(original, newContext);
    }

    @Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
        for (String prefix : sClassPrefixList) {
            try {
                View view = createView(name, prefix, attrs);
                if (view != null) {
                    return view;
                }
            } catch (ClassNotFoundException e) {
            }
        }

        return super.onCreateView(name, attrs);
    }

    public LayoutInflater cloneInContext(Context newContext) {
        return new PhoneLayoutInflater(this, newContext);
    }
}

onCreateView方法。该方法通过将传递过来的View前面加上"android.widget.","android.webkit.","android.app."用来得到该内置View对象的完整路径,最后根据路径来创建出对应的View。

2、接下来看createView(name,prefix,attrs)。

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加入到父视图中。

 

猜你喜欢

转载自blog.csdn.net/csdn_aiyang/article/details/86626748
今日推荐