LayoutInflater学习(一)之布局解析

LayoutInflater的创建与实例化

LayoutInflater是位于 "android.view" 包下的一个抽象类,同样它也是一个系统级服务

package android.view;
@SystemService(Context.LAYOUT_INFLATER_SERVICE)
public abstract class LayoutInflater {

LayoutInflater是用来解析 xml 布局文件,并创建对应的View对象,不管是系统级的布局文件还是开发者自己定义的xml布局文件都要用它来解析,一般通过下面的代码来解析布局.

LayoutInflater.from(this).inflate(R.layout.layout_normal_group, ll, false);

前面说了LayoutInflater是一个抽象类,那么它的实现类是谁,它又是怎么实例化的呢,其实去看LayoutInflater类的介绍也可以知道,因为LayoutInflater是一个系统服务,所以可以直接通过对应的Context上下文来获取LayoutInflater对象

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

除此之外还可以通过 LayoutInflater.from(context) 或者 Activity.getLayoutInflater,其实这两种获取方法最终还是通过上面的 getSystemService() 方法来获取的,知道了怎么获取LayoutInflater实例,但是LayoutInflater毕竟是一个抽象类,它的实现类到底是谁?

LayoutInflater的实现类是 PhoneLayoutInflater,其实它也就是重写了一个LayoutInflater的onCreateView()方法,并提供了一个cloneInContext()方法来客隆一个LayoutInflater实例

package com.android.internal.policy;
/**
 * @hide
 */
public class PhoneLayoutInflater extends LayoutInflater {
    ......
    public LayoutInflater cloneInContext(Context newContext) {
        return new PhoneLayoutInflater(this, newContext);
    }
}

PhoneLayoutInflater的创建是在SystemServiceRegistry中完成的,具体的细节这次就不再深究了

package android.app;
@SystemApi
public final class SystemServiceRegistry {
    ......
    static {
        ......
        registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
                 new CachedServiceFetcher<LayoutInflater>() {
            @Override
            public LayoutInflater createService(ContextImpl ctx) {
                return new PhoneLayoutInflater(ctx.getOuterContext());
            }});
        ......
    }

LayoutInflater的解析过程

接下来看下LayoutInflater解析xml布局的流程,上篇中提到了DecorView解析系统布局的一个方法

final View root = inflater.inflate(layoutResource, null);

再加上上文提到的另一个inflate方法,主要也就是使用这两个常用方法解析加载布局

LayoutInflater.from(this).inflate(R.layout.layout_normal_group, ll, false);

现在直接从这个方法入手看下解析的详细流程

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

可以看到主要流程还是在inflate(int,ViewGroup,boolean)方法里,直接看主要流程

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        ......
        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) {
            ......
            final Context inflaterContext = mContext;
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root;
            try {
                //通过XmlPullParser找到布局文件中tag为XmlPullParser.START_TAG的位置
                advanceToRootNode(parser);
                final String name = parser.getName();
                ......
                if (TAG_MERGE.equals(name)) {
                    ......
                } else {
                    // Temp is the root view that was found in the xml
                    //创建 xml 布局中最外层的View对象
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    ViewGroup.LayoutParams params = null;
                    if (root != null) {
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            temp.setLayoutParams(params);
                        }
                    }
                    rInflateChildren(parser, temp, attrs, true);
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } catch (XmlPullParserException e) {
               ......
            }
            return result;
        }
    }

首先 advanceToRootNode(XmlPullParser parser) 方法是通过XmlPullParser解析xml布局,找到xml布局中tag标签为"XmlPullParser.START_TAG"的位置,对于这个过程的具体流程我在之前的这篇文章里有记录:Android LayoutInflater inflate方法学习,有兴趣的可以去看下。

重点关注下inflate方法中的两个参数 root 参数以及 attachToRoot 参数

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) 

看字面意思也可以理解, root 是我们解析某个xml布局时传入的一个父容器ViewGroup,该ViewGroup并不属于xml布局,一般是用来存放你要解析的xml布局的一个父容器,例如我们经常使用的RecyclerView在它的适配器的onCreateViewHolder中经常传入的parent参数就是root参数。这里的parent参数就是对应的RecyclerView,还有另一个参数 attachToRoot,看字面意思理解就是:是否要将解析后的xml布局依附于 root 容器,也就是把解析后的xml布局放入到 root 容器中。

接下来通过具体代码来理解下这两个参数:

1. root 不为空, attachToRoot 为 false

if (TAG_MERGE.equals(name)) {
   ......
 } else {
   final View temp = createViewFromTag(root, name, inflaterContext, attrs);
   ViewGroup.LayoutParams params = null;
   if (root != null) {
      params = root.generateLayoutParams(attrs);
      if (!attachToRoot) {
         //root不为空,attachToRoot为false时的第一个作用:
         //设置了一下xml最外层View(ViewGroup)的LayoutParams
         temp.setLayoutParams(params);
      }
   }
   rInflateChildren(parser, temp, attrs, true);
   if (root != null && attachToRoot) {
      root.addView(temp, params);
   }
   if (root == null || !attachToRoot) {
      //root不为空,attachToRoot为false时的第二个作用:
      //inflate方法最终返回的ViewGroup(View)是xml布局的最外层的ViewGroup(View)
      result = temp;
   }
}

总结:当 root 不为空且 attachToRoot 为false时,inflate方法最终返回的View是xml布局中最外层的View,并且这个View的 LayoutParams 被设置了一下,也就是手动设置了该View的宽、高。

下面来通过一个简单的例子看下这种情况下解析的布局是什么效果,例子很简单

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  LinearLayout ll = findViewById(R.id.ll);
  View view = LayoutInflater.from(this).inflate(R.layout.layout_normal, ll, false);
  FrameLayout ff = findViewById(R.id.ff);
  ff.addView(view);
}

 来看下 activity_main.xml 和 layout_normal.xml 的布局

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/cs"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/ll"
        android:background="@color/purple_200"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.21">
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <FrameLayout
        android:id="@+id/ff"
        android:background="@color/purple_700"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.76">
    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

layout_normal.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView
    android:text="测试LayoutInflater inflate方法"
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:background="@color/teal_200"
    android:textColor="@color/white"
    xmlns:android="http://schemas.android.com/apk/res/android" />

 看下最终的效果

2. root 不为空, attachToRoot 为 true

if (TAG_MERGE.equals(name)) {
   ......
 } else {
   final View temp = createViewFromTag(root, name, inflaterContext, attrs);
   ViewGroup.LayoutParams params = null;
   if (root != null) {
      params = root.generateLayoutParams(attrs);
      if (!attachToRoot) {
         //root不为空,attachToRoot为true这里就不再执行了
         temp.setLayoutParams(params);
      }
   }
   rInflateChildren(parser, temp, attrs, true);
   if (root != null && attachToRoot) {
      //root不为空,attachToRoot为true时,xml的根视图View直接被
      //添加到 root 容器里了,并最终返回 root
      root.addView(temp, params);
   }
   if (root == null || !attachToRoot) {
      //root不为空,attachToRoot为true这里也不再执行了
      result = temp;
   }
}

总结:

(1). 当 attachToRoot 为 true 时会直接通过 root.addView(temp,params) 的方法把 整个xml布局添加到 root 容器里

(2). inflate方法最后返回的是 root ,而不是原来的 xml 布局最外层的View

还是上面 1 中的例子,我们如果仅仅把 attachToRoot 的参数改为true,然后直接运行就会报下面的错误信息,报错位置是在 MainAcitvity 中:ff.addView(view);

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
        at android.view.ViewGroup.addViewInner(ViewGroup.java:5235)
        at android.view.ViewGroup.addView(ViewGroup.java:5064)
        at android.view.ViewGroup.addView(ViewGroup.java:5004)
        at android.view.ViewGroup.addView(ViewGroup.java:4976)
        at com.github.layoutinflaterdemo.MainActivity.onCreate(MainActivity.java:22)

上面报错的原因就是因为:一个View只能有一个父亲,当我们通过 LayoutInflater.from(this).inflate(R.layout.layout_normal, ll, true); 来加载xml布局时,由于 attachToRoot为true,xml布局的最外层View已经被add到root中一次了,已经有了一个父View。所以现在对原来的onCreate中的代码做一下修改,修改后的代码如下: 

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  ConstraintLayout cs = findViewById(R.id.cs);
  LinearLayout ll = findViewById(R.id.ll);
  View view = LayoutInflater.from(this).inflate(R.layout.layout_normal, ll, true);
  FrameLayout ff = findViewById(R.id.ff);
  cs.removeView(view);
  ff.addView(view);
}

这里要注意的是,因为inflate方法中 attachToRoot 参数传的是 true,所以上面代码中inflate方法返回的view应该是id为 ll 的LinearLayout,而不再是之前的TextView了,这里 view 的 parent 是ConstraintLayout,所以需要先执行 cs.removeView(View); 最后看下效果。

 可以看到被添加的view最外层确实是原来的LinearLayout

3. root 为空的情况

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, inflaterContext, attrs, false);
 } else {
   final View temp = createViewFromTag(root, name, inflaterContext, attrs);
   ViewGroup.LayoutParams params = null;
   ......
   rInflateChildren(parser, temp, attrs, true);
   ......
   if (root == null || !attachToRoot) {
      //这里root为空时不管attachToRoot是true还是false最终都返回temp
      result = temp;
   }
}

总结:当需要加载的xml布局最外层标签不是<merge>时,如果 root 为空,不管 attachToRoot 是 true 还是 false,inflate 方法都将返回 xml布局的最外层View。

目录

LayoutInflater的创建与实例化

LayoutInflater的解析过程

1. root 不为空, attachToRoot 为 false

2. root 不为空, attachToRoot 为 true

3. root 为空的情况


但是如果要加载的xml布局最外层标签是 <merge>,当 root 为空时, 将直接抛出异常

下面看事例,还是对原来的例子做下简单的修改

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

  FrameLayout ff = findViewById(R.id.ff);
  View view = LayoutInflater.from(this).inflate(R.layout.layout_normal, null);

  ff.addView(view);
}

 最终效果:

细心的网友可能发现了问题,layout_normal 布局中只有一个TextView,并且xml中给的宽是“wrap_content”,高是固定值 50dp,而看最终效果明显跟xml布局中的宽高不一致,并且此时不管你怎么修改TextView的宽、高,最终的效果始终不变,看这个效果倒是像"match_parent"。 

原因分析:通过观察上面第3种情况时的源码就可以知道,当 root 为null时,我们通过LayoutInflater的 inflate 方法加载布局时,在 inflate方法中创建完成xml中最外层的View时,并没有为该View设置布局参数就直接返回了,所以此时 xml 布局中最外层布局的参数LayoutParams是无效的,也就是我们在 xml 中给最外层View设置的宽、高的参数是无效的。 

既然 root 为null时,通过LayoutInflater加载的布局,最外层View的宽、高的设置是无效的,为何上面的事例中最后的效果确像是"match_parent"? 这是因为:我们通过addView()方法向一个父容器中添加子View时,如果被添加的子View LayoutParams为空,这个时候会直接调用ViewGroup的方法 generateDefaultLayoutParams()来生产默认的布局参数,上面的事例是通过FrameLayout来添加的,我们看下FrameLayout的源码,发现FrameLayout重写了这个方法

FrameLayout.java

@Override
protected LayoutParams generateDefaultLayoutParams() {
   return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}

可以看到在 FrameLayout 中该方法默认给的宽高值,确实都是 "match_parent"。

由此我们可以得出:当使用 LayoutInflater 的 inflate()方法加载布局,并且 root 参数传了 null 时,我们如果还想要把解析后的 xml 布局添加到某个父容器中时,一定要给该布局最外层的View设置一个布局参数 LayoutParams,我们看下之前提到的DecorView中是怎么使用的

DecorView.java

void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
   ......
   mDecorCaptionView = createDecorCaptionView(inflater);
   //root为null时,需要为生成的View添加 LayoutParams
   final View root = inflater.inflate(layoutResource, null);
   if (mDecorCaptionView != null) {
       if (mDecorCaptionView.getParent() == null) {
         addView(mDecorCaptionView,
                new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
       }
       mDecorCaptionView.addView(root,
              new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT));
    } else {
      addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
    }
    mContentRoot = (ViewGroup) root;
    initializeElevation();
}

可以看到DecorView中在addView时都设置了对应的布局参数

同样的我们也来修改下之前的代码 

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

  FrameLayout ff = findViewById(R.id.ff);
  View view = LayoutInflater.from(this).inflate(R.layout.layout_normal, null);
  ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,dp2px(50));
  view.setLayoutParams(params);
  ff.addView(view);
}

int dp2px(final float dpValue) {
  final float scale = this.getResources().getDisplayMetrics().density;
  return (int) (dpValue * scale + 0.5f);
}

再来看下最终的效果,是不是达到了期望效果

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值