Android Inflate 的使用

在使用View.Inflate(context,resid,root)创建recyclerview item布局时,根布局的margin,pading都没有起作用.

看了它其中的源码使用的是LayoutInflater.from().inflate(),层层跟进发现其中有一段逻辑:

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
		.......省略代码
                final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                ViewGroup.LayoutParams params = null;
                if (root != null) {
                    // Create layout params that match root, if supplied
                    params = root.generateLayoutParams(attrs);
                    if (!attachToRoot) {
                        // Set the layout params for temp if we are not
                        // attaching. (If we are, we use addView, below)
                        temp.setLayoutParams(params);
                    }
                }
                // We are supposed to attach all the views we found (int temp)
                // to root. Do that now.
                if (root != null && attachToRoot) {
                    root.addView(temp, params);
                }
	.......省略代码
        return result;
    }
}

也就是说,root!=null && attachToRoot==true,会将布局view添加到内部,作为它的父view,否则不会设置布局的layoutparams,但是如果我们在使用recyclerview创建item布局时并不需要添加到父view怎么办?


可以看到attachToRoot(是否附加到根布局)只需将这个参数传false,布局将不会添加到root中,并且还会设置布局的layoutparams。

调用:

LayoutInflater.from(context).inflate(R.layout.item_layout,parent,false);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值