Android中布局加载器_LayoutInflater

2020-03-09  本文已影响0人  dashingqi

本文主要从如下几点学习LayoutInflater

LayoutInflater是啥

源码定义
Instantiates a layout XML file into its corresponding {@link android.view.View}
objects. It is never used directly. Instead, use
{@link android.app.Activity#getLayoutInflater()} or
{@link Context#getSystemService} to retrieve a standard LayoutInflater instance
that is already hooked up to the current context and correctly configured
for the device you are running on.

// 说的意思就是
  
 LayoutInflater是将XML布局文件实例化为View的对象。不要单独使用它,需要使用
 Activity.getLayoutInflater 或者使用 Context.getSystemService()来获取于
 当前Context相关联并且正确配置的LayoutInflater

LayutInflater的获取

这三种方式的对比

LayoutInflater的inflate方法

LayoutInflater类中有多个重载的inflate方法,但是这些方法最终都会调用下面这个方法

rInflate方法
createViewFromTag方法
createView方法

总结

infalte重载的方法
 public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
   // 当root不为null attachToRoot为true否则为false
        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) + ")");
        }

        View view = tryInflatePrecompiled(resource, res, root, attachToRoot);
        if (view != null) {
            return view;
        }

        XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }
    
    
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
      // 同样 root不为null attachToRoot为true 否则为false
        return inflate(parser, root, root != null);
    }

    
    //最终都会调用的inflate方法
     public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
上一篇下一篇

猜你喜欢

热点阅读