使用LayoutInflater的inflate方法的注意事项

获取LayoutInflater实例的常规方法

//方法1
LayoutInflater layoutInflater = LayoutInflater.from(context);  
//方法2
LayoutInflater layoutInflater = (LayoutInflater) context  
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

注意inflate方法的第二,第三个参数的使用

这里写图片描述
如上图所示:如果rootView不为空且attachToRoot为true,即传入rootVeiw且希望布局文件挂到RootView上,inflate方法返回的是rootView,否则返回inflate的View(布局文件中最外层的view,称之为布局文件的根view)

如下是关键的源码(View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)中的代码)

 //一开始
 View result = root;
 .....
 // Temp is the root view that was found in the xml
 final View temp = createViewFromTag(root, name, inflaterContext, attrs);

 // Decide whether to return the root that was passed in or the
 // top view found in xml.
 if (root == null || !attachToRoot) {
     result = temp;
 }

最常遇到的问题-布局文件的根View排版参数丢失了

如第二点提到的,如果第二个参数没有赋值,布局文件的排版版参数(LayoutParams)是不生效的(会丢失),关键代码如下图所示

// Temp is the root view that was found in the xml
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);
     }
}


// Inflate all children under temp against its context.
rInflateChildren(parser, temp, attrs, true);                  
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
    //addView的内部也会设置布局文件的根view的排版参数
    root.addView(temp, params);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值