LayoutInflater源码解析

Posted showCar

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LayoutInflater源码解析相关的知识,希望对你有一定的参考价值。

又来一篇源码分析文章。讲源码分析文章有的时候很虚,因为我只能讲个我看懂的大概流程,所以细节部分可以没有深入研究,看完之后也只能了解个大概。但个人觉得看源码更重要的是思路而不是细节。今天来分析下LayoutInflater的源码。
之所以分析它是因为我们来常经常使用到它,但往往只知道它是加载view的而不知它具体的实现方法。不多说直接分析。

源码分析

平常我们使用LayoutInflater最常见的方式如:

 LayoutInflater inflate = LayoutInflater.from(Context context); LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

这两种方式实质上是一样的。看来LayoutInflater.from的源码:

 public static LayoutInflater from(Context context) 
        LayoutInflater LayoutInflater =
                (LayoutInflater) context .getSystemService(Context. LAYOUT_INFLATER_SERVICE);
        if ( LayoutInflater == null) 
            throw new AssertionError( "LayoutInflater not found.");
        
        return LayoutInflater;
    

好吧,它就是一个披着context .getSystemService皮的狼。其实就是简单的封装了下。平常我们在获取系统的一些service如获取传感器之类的都会用到getSystemService,那么在这里context .getSystemService又是具体怎么实现的。

getSystemService

了解这个问题之前我们要清楚,Context是什么,平时我们经常说Context是上下文环境。其实Application,Activity,Service都会存在一个Context。它的具体实现类是ContextImpl。那么直接看ContextImpl:

  @Override
    public Object getSystemService(String name) 
        ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);
        return fetcher == null ? null : fetcher.getService(this);
    

SYSTEM_SERVICE_MAP是什么。我们继续看ContextImpl的代码:

class ContextImpl extends Context 
    private final static String TAG = "ContextImpl";
    private final static boolean DEBUG = false;

    /**
     * Map from package name, to preference name, to cached preferences.
     */
    private static ArrayMap<String, ArrayMap<String, SharedPreferencesImpl>> sSharedPrefs;



    /**
     * Override this class when the system service constructor needs a
     * ContextImpl.  Else, use StaticServiceFetcher below.
     */
    /*package*/ static class ServiceFetcher 
        int mContextCacheIndex = -1;

        /**
         * Main entrypoint; only override if you don't need caching.
         */
        public Object getService(ContextImpl ctx) 
            ArrayList<Object> cache = ctx.mServiceCache;
            Object service;
            synchronized (cache) 
                if (cache.size() == 0) 
                    // Initialize the cache vector on first access.
                    // At this point sNextPerContextServiceCacheIndex
                    // is the number of potential services that are
                    // cached per-Context.
                    for (int i = 0; i < sNextPerContextServiceCacheIndex; i++) 
                        cache.add(null);
                    
                 else 
                    service = cache.get(mContextCacheIndex);
                    if (service != null) 
                        return service;
                    
                
                service = createService(ctx);
                cache.set(mContextCacheIndex, service);
                return service;
            
        

        /**
         * Override this to create a new per-Context instance of the
         * service.  getService() will handle locking and caching.
         */
        public Object createService(ContextImpl ctx) 
            throw new RuntimeException("Not implemented");
        
    
abstract static class StaticServiceFetcher extends ServiceFetcher 
        private Object mCachedInstance;

        @Override
        public final Object getService(ContextImpl unused) 
            synchronized (StaticServiceFetcher.this) 
                Object service = mCachedInstance;
                if (service != null) 
                    return service;
                
                return mCachedInstance = createStaticService();
            
        

        public abstract Object createStaticService();
    

    private static final HashMap<String, ServiceFetcher> SYSTEM_SERVICE_MAP =
            new HashMap<String, ServiceFetcher>();

    private static int sNextPerContextServiceCacheIndex = 0;
    private static void registerService(String serviceName, ServiceFetcher fetcher) 
        if (!(fetcher instanceof StaticServiceFetcher)) 
            fetcher.mContextCacheIndex = sNextPerContextServiceCacheIndex++;
        
        SYSTEM_SERVICE_MAP.put(serviceName, fetcher);
    
 static 
…………
registerService(LAYOUT_INFLATER_SERVICE, new ServiceFetcher() 
                public Object createService(ContextImpl ctx) 
                    return PolicyManager.makeNewLayoutInflater(ctx.getOuterContext());
                );
…………

在虚拟机第一次加载该类时就会注册各种ServiceFatcher,包括LayoutInflater,这个是在一系列的registerService中实现的。然后将它们存储在SYSTEM_SERVICE_MAP这个HashMap中,以后要用只需从中获取,注册是在静态代码块中进行的,也就是说它只会执行一次,保证实例的唯一性。这可以说是用容器来实现的单例模式。最后通过getSystemService获取相应的Service。
我们重点关注到PolicyManager.makeNewLayoutInflate这句代码,它最终调用的是Policy中的makeNewLayoutInflate方法。

public class Policy implements IPolicy 
    private static final String TAG = "PhonePolicy";
    static 
        // For performance reasons, preload some policy specific classes when
        // the policy gets loaded.
        for (String s : preload_classes) 
            try 
                Class.forName(s);
             catch (ClassNotFoundException ex) 
                Log.e(TAG, "Could not preload class for phone policy: " + s);
            
        
    

    public Window makeNewWindow(Context context) 
        return new PhoneWindow(context);
    

    public LayoutInflater makeNewLayoutInflater(Context context) 
        return new PhoneLayoutInflater(context);
    

在这里看到Window具体实现类是PhoneWindow,LayoutInflater的具体实现是PhoneLayoutInflater。

PhoneLayoutInflater

看下PhoneLayoutInflater的代码。

public class PhoneLayoutInflater extends LayoutInflater 
    private static final String[] sClassPrefixList = 
        "android.widget.",
        "android.webkit.",
        "android.app."
    ;

    /**
     * Instead of instantiating directly, you should retrieve an instance
     * through @link Context#getSystemService
     * 
     * @param context The Context in which in which to find resources and other
     *                application-specific things.
     * 
     * @see Context#getSystemService
     */
    public PhoneLayoutInflater(Context context) 
        super(context);
    

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

    /** Override onCreateView to instantiate names that correspond to the
        widgets known to the Widget factory. If we don't find a match,
        call through to our super class.
    */
    @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) 
                // In this case we want to let the base class take a crack
                // at it.
            
        

        return super.onCreateView(name, attrs);
    

它重定了onCreateView 方法,其实就是为系统View加上相应的前缀。如TextView读出的完整路径会是android.widget.TextView。再调用createView方法,通过类的完整路径来构造View对象。具体的实现过程我们可以来看看setContentView。

setContentView

首先我们来看一幅android的结构图:

Acitivity的一个界面中最外层是PhoneWindow,它里面是一个DecorView。它是界面中所有view的根view。它包括两部分,ActionBar和ContentView,而ContentView就是我们平常接触最多的,setContentView设置的就是它的内容。而我们在xml中定义的所有view都是显示在它上面的。
先来看下PhoneWindow中的setContentView方法。

  public void setContentView(int layoutResID) 
        // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
        // decor, when theme attributes and the like are crystalized. Do not check the feature
        // before this happens.
        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);
        
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) 
            cb.onContentChanged();
        

首先调用的是installDecor方法。从名字中我们就可以猜到,它应该就是加载DecorView。看下代码:

private void installDecor() 
        if (mDecor == null) 
            mDecor = generateDecor();
            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) 
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            
        
        if (mContentParent == null) 
            mContentParent = generateLayout(mDecor);

            // Set up decor part of UI to ignore fitsSystemWindows if appropriate.
            mDecor.makeOptionalFitsSystemWindows();

            final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
                    R.id.decor_content_parent);

            if (decorContentParent != null) 
                mDecorContentParent = decorContentParent;
                mDecorContentParent.setWindowCallback(getCallback());
                if (mDecorContentParent.getTitle() == null) 
                    mDecorContentParent.setWindowTitle(mTitle);
                

                final int localFeatures = getLocalFeatures();
                for (int i = 0; i < FEATURE_MAX; i++) 
                    if ((localFeatures & (1 << i)) != 0) 
                        mDecorContentParent.initFeature(i);
                    
                

                mDecorContentParent.setUiOptions(mUiOptions);

                if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) != 0 ||
                        (mIconRes != 0 && !mDecorContentParent.hasIcon())) 
                    mDecorContentParent.setIcon(mIconRes);
                 else if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) == 0 &&
                        mIconRes == 0 && !mDecorContentParent.hasIcon()) 
                    mDecorContentParent.setIcon(
                            getContext().getPackageManager().getDefaultActivityIcon());
                    mResourcesSetFlags |= FLAG_RESOURCE_SET_ICON_FALLBACK;
                
                if ((mResourcesSetFlags & FLAG_RESOURCE_SET_LOGO) != 0 ||
                        (mLogoRes != 0 && !mDecorContentParent.hasLogo())) 
                    mDecorContentParent.setLogo(mLogoRes);
                

                // Invalidate if the panel menu hasn't been created before this.
                // Panel menu invalidation is deferred avoiding application onCreateOptionsMenu
                // being called in the middle of onCreate or similar.
                // A pending invalidation will typically be resolved before the posted message
                // would run normally in order to satisfy instance state restoration.
                PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
                if (!isDestroyed() && (st == null || st.menu == null)) 
                    invalidatePanelMenu(FEATURE_ACTION_BAR);
                
             else 
                mTitleView = (TextView)findViewById(R.id.title);
                if (mTitleView != null) 
                    mTitleView.setLayoutDirection(mDecor.getLayoutDirection());
                    if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) 
                        View titleContainer = findViewById(
                                R.id.title_container);
                        if (titleContainer != null) 
                            titleContainer.setVisibility(View.GONE);
                         else 
                            mTitleView.setVisibility(View.GONE);
                        
                        if (mContentParent instanceof FrameLayout) 
                            ((FrameLayout)mContentParent).setForeground(null);
                        
                     else 
                        mTitleView.setText(mTitle);
                    
                
            

            if (mDecor.getBackground() == null && mBackgroundFallbackResource != 0) 
                mDecor.setBackgroundFallback(mBackgroundFallbackResource);
            

            // Only inflate or create a new TransitionManager if the caller hasn't
            // already set a custom one.
            if (hasFeature(FEATURE_ACTIVITY_TRANSITIONS)) 
                if (mTransitionManager == null) 
                    final int transitionRes = getWindowStyle().getResourceId(
                            R.styleable.Window_windowContentTransitionManager,
                            0);
                    if (transitionRes != 0) 
                        final TransitionInflater inflater = TransitionInflater.from(getContext());
                        mTransitionManager = inflater.inflateTransitionManager(transitionRes,
                                mContentParent);
                     else 
                        mTransitionManager = new TransitionManager();
                    
                

                mEnterTransition = getTransition(mEnterTransition, null,
                        R.styleable.Window_windowEnterTransition);
                mReturnTransition = getTransition(mReturnTransition, USE_DEFAULT_TRANSITION,
                        R.styleable.Window_windowReturnTransition);
                mExitTransition = getTransition(mExitTransition, null,
                        R.styleable.Window_windowExitTransition);
                mReenterTransition = getTransition(mReenterTransition, USE_DEFAULT_TRANSITION,
                        R.styleable.Window_windowReenterTransition);
                mSharedElementEnterTransition = getTransition(mSharedElementEnterTransition, null,
                        R.styleable.Window_windowSharedElementEnterTransition);
                mSharedElementReturnTransition = getTransition(mSharedElementReturnTransition,
                        USE_DEFAULT_TRANSITION,
                        R.styleable.Window_windowSharedElementReturnTransition);
                mSharedElementExitTransition = getTransition(mSharedElementExitTransition, null,
                        R.styleable.Window_windowSharedElementExitTransition);
                mSharedElementReenterTransition = getTransition(mSharedElementReenterTransition,
                        USE_DEFAULT_TRANSITION,
                        R.styleable.Window_windowSharedElementReenterTransition);
                if (mAllowEnterTransitionOverlap == null) 
                    mAllowEnterTransitionOverlap = getWindowStyle().getBoolean(
                            R.styleable.Window_windowAllowEnterTransitionOverlap, true);
                
                if (mAllowReturnTransitionOverlap == null) 
                    mAllowReturnTransitionOverlap = getWindowStyle().getBoolean(
                            R.styleable.Window_windowAllowReturnTransitionOverlap, true);
                
                if (mBackgroundFadeDurationMillis < 0) 
                    mBackgroundFadeDurationMillis = getWindowStyle().getInteger(
                            R.styleable.Window_windowTransitionBackgroundFadeDuration,
                            DEFAULT_BACKGROUND_FADE_DURATION_MS);
                
                if (mSharedElementsUseOverlay == null) 
                    mSharedElementsUseOverlay = getWindowStyle().getBoolean(
                            R.styleable.Window_windowSharedElementsUseOverlay, true);
                
            
        
    

可以看到这里不仅初始化mContentParent,而且在之前先调用generateDecor();初始化了一个mDecor,mDecor是DecorView对象,为FrameLayout的子类。并通过findViewById进行获取控件。
generateLayout(mDecor)猜测应该是用来获取到了我们的ContentView的;具体我们来看下源码。

generateLayout

protected ViewGroup generateLayout(DecorView decor)  
// Apply data from current theme. 
TypedArray a = getWindowStyle(); 
//...... //依据主题style设置一堆值进行设置 
int layoutResource;
 int features = getLocalFeatures();

View in = mLayoutInflater.inflate(layoutResource, null); 
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); 
mContentRoot = (ViewGroup) in;
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT); 
if (contentParent == null) 

throw new RuntimeException("Window couldn't find content container view");
 //...... //继续一堆属性设置,完事返回contentParent
 return contentParent;
  

之前我们设置界面主题(如Notitle)主要有两种方式,一种是在xml中设置:

 android:theme="@android:style/Theme.Black.NoTitleBar" 

一种是调用requestFeature。

requestWindowFeature(Window.FEATURE_NO_TITLE);

第一种方法对应的就是getWindowStyle方法。而第二种就是在getLocalFeatures完成的。这就是为什么requestWindowFeature要写在setContentView方法之前的原因。
接着通过mDecor.findViewById传入R.id.content,返回mDecor(布局)中的id为content的View,就是我们前面说的ContentView。可以看到我们的mDecor是一个FrameLayout,然后会根据theme去选择系统中的布局文件,将布局文件通过inflate转化为view,加入到mDecor中;这些布局文件中都包含一个id为content的FrameLayout,将其引用返回给mContentParent。
等我们的mContentParent有值了以后,再次回到setContentView中,它会调用以下方法。

 mLayoutInflater.inflate(layoutResID, mContentParent);

接下来重点看inflate是如何加载布局的。

inflate

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

            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context)mConstructorArgs[0];
            mConstructorArgs[0] = mContext;
            View result = root;

            try 
                // Look for the root node.
                int type;
                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();

                if (DEBUG) 
                    System.out.println("**************************");
                    System.out.println("Creating root view: "
                            + name);
                    System.out.println("**************************");
                

                if (TAG_MERGE.equals(name)) 
                    if (root == null || !attachToRoot) 
                        throw new InflateException("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    

                    rInflate(parser, root, attrs, false, false);
                 else 
                    // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, attrs, false);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) 
                        if (DEBUG) 
                            System.out.println("Creating params from root: " +
                                    root);
                        
                        // Create layout params that match root, if supplied
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) 
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        
                    

                    if (DEBUG) 
                        System.out.println("-----> start inflating children");
                    
                    // Inflate all children under temp
                    rInflate(parser, temp, attrs, true, true);
                    if (DEBUG) 
                        System.out.println("-----> done inflating children");
                    

                    // We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    if (root != null && attachToRoot) 
                        root.addView(temp, params);
                    

                    // Decide whether to return the root that was passed in or the
                    // top view found in xml.
                    if (root == null || !attachToRoot) 
                        result = temp;
                    
                

             catch (XmlPullParserException e) 
                InflateException ex = new InflateException(e.getMessage());
                ex.initCause(e);
                throw ex;
             catch (IOException e) 
                InflateException ex = new InflateException(
                        parser.getPositionDescription()
                        + ": " + e.getMessage());
                ex.initCause(e);
                throw ex;
             finally 
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;
            

            Trace.traceEnd(Trace.TRACE_TAG_VIEW);

            return result;
        
    

代码很长,主要分为以下几步:
1.解析XML的根标签。
2.如果是merge,调用rInflate进行解析。它会把merge所有子view添加到根标签中。
3.如果是普通标签,调用createViewFromTag进行解析。
4.调用rInflate解析temp根元素下的子view。并添加到temp中。
最后返回root。
看下createViewFromTag是如何加载标签的。

View createViewFromTag(View parent, String name, AttributeSet attrs, boolean inheritContext) 
        if (name.equals("view")) 
            name = attrs.getAttributeValue(null, "class");
        

        Context viewContext;
        if (parent != null && inheritContext) 
            viewContext = parent.getContext();
         else 
            viewContext = mContext;
        

        // Apply a theme wrapper, if requested.
        final TypedArray ta = viewContext.obtainStyledAttributes(attrs, ATTRS_THEME);
        final int themeResId = ta.getResourceId(0, 0);
        if (themeResId != 0) 
            viewContext = new ContextThemeWrapper(viewContext, themeResId);
        
        ta.recycle();

        if (name.equals(TAG_1995)) 
            // Let's party like it's 1995!
            return new BlinkLayout(viewContext, attrs);
        

        if (DEBUG) System.out.println("******** Creating view: " + name);

        try 
            View view;
            if (mFactory2 != null) 
                view = mFactory2.onCreateView(parent, name, viewContext, attrs);
             else if (mFactory != null) 
                view = mFactory.onCreateView(name, viewContext, attrs);
             else 
                view = null;
            

            if (view == null && mPrivateFactory != null) 
                view = mPrivateFactory.onCreateView(parent, name, viewContext, attrs);
            

            if (view == null) 
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = viewContext;
                try 
                    if (-1 == name.indexOf('.')) 
                        view = onCreateView(parent, name, attrs);
                     else 
                        view = createView(name, null, attrs);
                    
                 finally 
                    mConstructorArgs[0] = lastContext;
                
            

            if (DEBUG) System.out.println("Created view is: " + view);
            return view;

         catch (InflateException e) 
            throw e;

         catch (ClassNotFoundException e) 
            InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Error inflating class " + name);
            ie.initCause(e);
            throw ie;

         catch (Exception e) 
            InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Error inflating class " + name);
            ie.initCause(e);
            throw ie;
        
    

上面这个方法中,如果传过来的名字没有“.”,会认为是一个内置view。会调用onCreateView来解析这个View。PhoneLayoutInflater的onCreateView就是为内置的View加上前缀,如android.widget等。然后再调用createView()来进行view的构造。

 public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException 
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        Class<? extends View> clazz = null;

        try 
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
          //constructor是从缓存中取出的构造函数
            if (constructor == null) 
                // Class not found in the cache, see if it's real, and try to add it
//如果prefix不为空就构造view路径并加载
                clazz = mContext.getClassLoader().loadClass(
                        prefix != null ? (prefix + name) : name).asSubclass(View.class);

                if (mFilter != null && clazz != null) 
                    boolean allowed = mFilter.onLoadClass(clazz);
                    if (!allowed) 
                        failNotAllowed(name, prefix, attrs);
                    
                
                constructor = clazz.getConstructor(mConstructorSignature);
                sConstructorMap.put(name, constructor);
             else 
                // If we have a filter, apply it to cached constructor
                if (mFilter != null) 
                    // Have we seen this name before?
                    Boolean allowedState = mFilterMap.get(name);
                    if (allowedState == null) 
                        // New class -- remember whether it is allowed
//通过反射构造view
                        clazz = mContext.getClassLoader().loadClass(
                                prefix != null ? (prefix + name) : name).asSubclass(View.class);

                        boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                        mFilterMap.put(name, allowed);
                        if (!allowed) 
                            failNotAllowed(name, prefix, attrs);
                        
                     else if (allowedState.equals(Boolean.FALSE)) 
                        failNotAllowed(name, prefix, attrs);
                    
                
            

            Object[] args = mConstructorArgs;
            args[1] = attrs;

            constructor.setAccessible(true);
            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;

         catch (NoSuchMethodException e) 
            InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Error inflating class "
                    + (prefix != null ? (prefix + name) : name));
            ie.initCause(e);
            throw ie;

         catch (ClassCastException e) 
            // If loaded class is not a View subclass
            InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Class is not a View "
                    + (prefix != null ? (prefix + name) : name));
            ie.initCause(e);
            throw ie;
         catch (ClassNotFoundException e) 
            // If loadClass fails, we should propagate the exception.
            throw e;
         catch (Exception e) 
            InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Error inflating class "
                    + (clazz == null ? "<unknown>" : clazz.getName()));
            ie.initCause(e);
            throw ie;
         finally 
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        
    

又是一大堆代码,但它其实就是使用view的完整路径将类加载到虚拟机中,通过构造函数来创建view对象,这个过程是通过反射。最后返回view。这个就解析了单个view。那如果是一棵树,则交给rInflate来处理。看下代码:

void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
            boolean finishInflate, boolean inheritContext) 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)) 
                parseViewTag(parser, parent, attrs);
             else if (TAG_INCLUDE.equals(name)) 
                if (parser.getDepth() == 0) 
                    throw new InflateException("<include /> cannot be the root element");
                
                parseInclude(parser, parent, attrs, inheritContext);
             else if (TAG_MERGE.equals(name)) 
                throw new InflateException("<merge /> must be the root element");
             else 
                final View view = createViewFromTag(parent, name, attrs, inheritContext);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflate(parser, view, attrs, true, true);
                viewGroup.addView(view, params);
            
        

        if (finishInflate) parent.onFinishInflate();
    

    /**
     * Parses a <code>&lt;request-focus&gt;</code> element and requests focus on
     * the containing View.
     */
    private void parseRequestFocus(XmlPullParser parser, View view)
            throws XmlPullParserException, IOException 
        int type;
        view.requestFocus();
        final int currentDepth = parser.getDepth();
        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > currentDepth) && type != XmlPullParser.END_DOCUMENT) 
            // Empty
        
    

普希金通过深度优先遍历来构造视图树。每解析一个view就会递归调用rInflate。view的结构一层包一层,其实就是标准的组合设计模式实现的。整个视图构建完后就会在onResume之后,内容就会出现在界面中。
到此,LayoutInflater加载View的过程就分析完了。还是比较简单易懂的。

布局加载优化

通过上面的分析,我们可以提出几点常用的布局优化手段:
1.尽量使用相对布局,减少不必要层级结构。
2.使用merge属性。使用它可以有效的将某些符合条件的多余的层级优化掉,使用merge标签还是有一些限制的,具体是:merge只能用在布局XML文件的根元素;使用merge来inflate一个布局时,必须指定一个ViewGroup作为其父元素,并且要设置inflate的attachToRoot参数为true。;不能在ViewStub中使用merge标签。
3.使用ViewStub。一个轻量级的页面,我们通常使用它来做预加载处理,来改善页面加载速度和提高流畅性,ViewStub本身不会占用层级,它最终会被它指定的层级取代。ViewStub也是有一些缺点,譬如:ViewStub只能Inflate一次,之后ViewStub对象会被置为空。VIewStub中不能嵌套merge标签。
4.使用include。这个标签是为了布局重用。
当然还有很多优化手段和工具可以使用,在此不一一罗列。关于布局还是有很大的学问要去深入研究的。

以上是关于LayoutInflater源码解析的主要内容,如果未能解决你的问题,请参考以下文章

Android LayoutInflater&LayoutInflaterCompat源码解析

LayoutInflater效率分析及源码跟踪

[Android FrameWork 6.0源码学习] LayoutInflater 类分析

Android LayoutInflater

android setContentView()源码解析

android setContentView()源码解析