LayoutInflater原理分析

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);

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

结论: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);

    }

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值