使用LayoutInflater应该注意的问题

我的博客原文地址

我们通常使用addView这个方法时,会先通过LayoutInflaterinflate生成一个View视图,然后添加到当前ViewGroup中,如果使用不恰当,就会出现这样的问题:

        setContentView(R.layout.layout_inflate_test);
        LinearLayout viewGroup = (LinearLayout) findViewById(R.id.root);

        //1.inflate_test根布局layout参数被忽略
//        View v = LayoutInflater.from(this).inflate(R.layout.inflate_test, null);
//        viewGroup.addView(v);

        //2.不会忽略
//        View v = LayoutInflater.from(this).inflate(R.layout.inflate_test, viewGroup, false);
//        viewGroup.addView(v);

        //3.不会忽略
//        LayoutInflater.from(this).inflate(R.layout.inflate_test, viewGroup);

        //4.不会忽略
//        LayoutInflater.from(this).inflate(R.layout.inflate_test, viewGroup, true);

上面的代码中,第一种用法根布局layout参数会被忽略,后面都不会。我们从LayoutInflater源码中可以看出来原因,在public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)方法中:

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

如果root不为空,且attachToRootfalse,会把布局参数params加上。

                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

如果root不为空,且attachToRoottrue,会通过addView(temp, params)方法加上布局参数。
因此,我们不能因为暂时不需要绑定到root上面就忽视掉root的作用,没有的话设置的布局参数就不起作用了哦!
比如我们在使用ListView的时候就经常碰到,ListView 添加HeaderView之后尺寸布局被忽略的情况:
通常添加头部的方法是

LayoutInflater lif = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View headerView = lif.inflate(R.layout.header, null);
mListView.addHeaderView(headerView);

原因就是lif.inflate(R.layout.header, null)丢失了XML布局中根ViewLayoutParam,其实使用下面的方法就可以了:

lif.inflate(R.layout.header, mListView, false);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寒江蓑笠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值