LayoutInflater参数的使用

LayoutInflater一个方法,原型为:

 public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 

这个方法有两个重要的参数root和attachToRoot,那么这两个参数会影响什么呢?

一、返回对象

返回对象不一定是xml对应的View对象,可能是传进去的参数root

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

上面是inflate方法的一段,如果root为null或者attachToRoot为false,那么将temp赋值给result,temp代表xml对应的View对象。由于这个方法返回的是result,result在前面已经赋过一次值,将root赋值给了result,如果这里不赋值的话,就会返回root。
因此仅仅根据上面一小段代码,就能总结出如下规律:

如果root=null或者attachToRoot=false,返回xml对应的对象。否则返回root。

二、布局参数

以前我碰到过这样一个例子,xml文件只有一个ImageView,ImageView的参数如下:

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="15dp"
    android:layout_height="15dp"
    android:background="#00ff00" />

然后在代码里面inflate一个对象,并加入到父布局中:

View view = LayoutInflater.from(getApplicationContext()).inflate(
				R.layout.text, null, false);
		ll.addView(view);

注意这里我的参数是root=null,attachToRoot为false,那么返回的肯定是一个ImageView对象,然而结果却有问题,就是界面上什么都没有,为什么会这样呢?
答案就在源码中,原因是ImageView的布局参数被换成了WRAP_CONTENT形式,在源码中可以找到当root不为nul时,布局参数会被传给ImageView对象:

if (root != null) {
                        if (DEBUG) {
                            System.out.println("Creating params from root: " +
                                    root);
                        }
                        // 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);
                        }
                    }
                  ..........
                  if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

上面都是root不为null时布局参数的传递,但是当root为null时,布局参数就丢失了。当我们把view手动添加到父布局中,父布局会给ImageView一个默认的布局方式,也就是WRAP_CONTENT,当ImageView的布局参数为WRAP_CONTENT并且没有指定drawable对象时,在测量时,就会把宽高都设置成0(具体见ImageView的onMeasure方法),这也就是为什么上面的写法什么都看不到的原音了,既然发现了原因那么怎么改呢。很简单也就是在inflate方法中直接就传入一个父布局,不论attachToRoot是否是true,都会给ImageView指定layout属性.

总结

inflate方法的参数会影响返回结果和view的布局参数,一般使用的时候最好指定父布局,是否添加到父容器中就要看需求了,如果想要inflate方法返回view对象,就设置false,并且后面手动使用父布局的addView方法.如果对返回值无所谓,就设置true。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值