LayoutInflater.inflate(int resource, ViewGroup root, boolean attachToRoot)的使用 《转》

inflate(int resource, ViewGroup root, boolean attachToRoot)
第一个参数传入布局的资源ID,生成fragment视图,第二个参数是视图的父视图,通常我们需要父
视图来正确配置组件。第三个参数告知布局生成器是否将生成的视图添加给父视图。
root不为空的情况:
1.如果attachToRoot为true,就直接将这个布局添加到root父布局了,并且返回的view就是父布局
2.如果attachToRoot为false,就不会添加这个布局到root父布局,返回的view为resource指定的布局

root为空的情况:
View view = View.inflate(context, R.layout.button_layout, null);
其实等价于:LayoutInflater.from(this).layoutInflater.inflate(R.layout.button_layout, null);

那么root为不为空有什么影响呢?
1.如果root为null,attachToRoot将失去作用,设置任何值都没有意义。同时这个布局的最外层参数就没有效了
2.如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,
    当该view被添加到父view当中时,这些layout属性会自动生效。
3.如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。

 其实View必须存在于一个父布局中,这样layout_width和layout_height才会有效,
这也是为什么这两个属性叫作layout_width和layout_height,而不是width和height。
所以:inflate(int resource, ViewGroup root, boolean attachToRoot)的第二个参数不为空,resource的最外层布局参数才会有效,否则就无效了
例子:item的布局文件如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="100dp">

    <TextView
        android:id="@+id/textView"
        android:textSize="30sp"
        android:gravity="center"
        android:background="#ffcccc"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

 

如果我是这样加载这个布局:

View view= LayoutInflater.from(context).inflate(R.layout.recycler_item_layout,parent,false);

效果如下:  可见在item布局中设置的宽高都有效

如果我是这样加载布局:   

View view = View.inflate(context, R.layout.recycler_item_layout, null);

 效果图如下:   可见在item设置的宽高都无效,如果你在LinearLayout中设置宽高的长度为固定值100dp,这样也是没有效果的,但是如果是在TextView中设置宽高为固定值,这样是有效的

原因也就是layout_height是在父布局中的高度,你要是都没有父布局,它又怎么能知道你的match_parent是多大呢?,最后也就只能包裹内容了.

转自 https://www.cnblogs.com/tangs/articles/5913719.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值