LayoutInflater主要是用于加载布局的,包括Activity中调用setContentView()内部也是通过LayoutInflater方法实现的。获取LayoutInflater常用的基本方法:

LayoutInflater layoutInflater = LayoutInflater.from(context);
LayoutInflater layoutInflater = getLayoutInflater()
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

接下来就可以使用​​layoutInflater.inflate​​布局了

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

1.如果root为空,那么attachToRoot将无效
2.如果root不为空,attachToRoot为true,那么view将自动作为子view添加到root布局内。
3.如果root不为空,attachToRoot为false,那么view将应用布局文件中最外层的所有layout属性,说白了就是使最外层的layout_width,layout_height等layout属性生效。
总结一句话:
root为空,最外层的所有layout属性无效,
root不为空,最外层的所有layout属性生效,

下面以一个Button进行说明,最外层设置layout_width,layout_height两个属性。

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:text="test"
android:layout_width="match_parent"
android:layout_height="200dp">
</Button>
  • root为空,attachToRoot 为true或者false效果,最外层layout属性无效
//View view = getLayoutInflater().inflate(R.layout.button_layout,null,false);
View view = getLayoutInflater().inflate(R.layout.button_layout,null,true);
mTopLayout.addView(view);

LayoutInflater原理分析_setContentView

  • root不为空,attachToRoot 为true效果
//因为这里attachToRoot 为true,所以不能再重复addview了
View view = getLayoutInflater().inflate(R.layout.button_layout,mTopLayout,true);

LayoutInflater原理分析_LayoutInflater_02

  • root不为空,attachToRoot 为false效果
View view = getLayoutInflater().inflate(R.layout.button_layout,mTopLayout,false);
mTopLayout.addView(view);

LayoutInflater原理分析_LayoutInflater_02

结论:View必须存在一个布局中,layout属性才会生效,否则无效。

看到这里,也许有些朋友心中会有一个巨大的疑惑。不对呀!平时在Activity中指定布局文件的时候,最外层的那个布局是可以指定大小的呀,layout_width和layout_height都是有作用的。确实,这主要是因为,在setContentView()方法中,Android会自动在布局文件的最外层再嵌套一个FrameLayout,所以layout_width和layout_height属性才会有效果。那么我们来证实一下吧

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_owner_draw);

mTopLayout = findViewById(R.id.layout_top);
ViewParent parent = mTopLayout.getParent();
Log.i(TAG, "onCreate: "+parent);

}

LayoutInflater原理分析_xml_04


其实任何一个Activity中显示的界面其实主要都由两部分组成,标题栏和内容布局。标题栏就是在很多界面顶部显示的那部分内容。而内容布局就是一个FrameLayout,这个布局的id叫作content,我们调用setContentView()方法时所传入的布局其实就是放到这个FrameLayout中的,这也是为什么这个方法名叫作setContentView(),而不是叫setView()。

LayoutInflater原理分析_LayoutInflater_05

​​Android LayoutInflater原理分析,带你一步步深入了解View(一)​​