LayoutInflater 填充器填充布局,布局属性失效问题

本文探讨了在使用LayoutInflater填充布局时遇到的宽高失效问题。通过分析源码,揭示了inflate方法的两个重载版本的工作原理,并提供了三种不同的解决方案,包括重新设置布局参数、手动转换dp和px以及利用attachToRoot参数正确添加View。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

无意间看到一个帖子,标题:一个难倒 3年 android开发经验 ” 工程师 ” 的 “bug”,链接地址:http://www.2cto.com/kf/201602/489364.html,所描述的问题就是通过填充器动态添加View对象的时候发现view中的宽高失效,而原帖作者所采用的方式是重新设置布局参数,方法如下代码所示:

        ll_container=(LinearLayout) findViewById(R.id.ll_container);
        btn=(Button) LayoutInflater.from(this).inflate(R.layout.my_button, null);
        LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(200,200);
        btn.setLayoutParams(lp);
        ll_container.addView(btn);

看到这个问题之后非常怀疑,觉得非常奇怪,为什么原来xml中的宽度和高度消失了,也是带着这个疑问开始各种搜索,最后通过查看源代码得到了答案,在这里分享给大家。
首先inflate有两个供用户调用的重载方法,分别是:
1、 public View inflate(int resource, ViewGroup root)
2、public View inflate(int resource, ViewGroup root, boolean attachToRoot)
而我们常用的是第一个,而且习惯将root设置为null;
先看第一个方法的源码:

 public View inflate(int resource, ViewGroup root) {
        return inflate(resource, root, root != null);
    }

看见了吗,其实也是调用的而第二个重载方法,三个参数分别是:view的资源id,装载view的父容器,是否依附到父容器的布尔标记。
下面我们就要进入inflate(int resource, ViewGroup root, boolean attachToRoot)源码中,

 public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
        if (DEBUG) System.out.println("INFLATING from resource: " + resource);
        XmlResourceParser parser = getContext().getResources().getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

这个方法其实做的事情就是将view的xml文件读取到xml解析器中,然后传递到另外一个inflate重载方法中,
最核心的就在这个方法中,下面来看这个方法中的源代码:

      public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context)mConstructorArgs[0];
            mConstructorArgs[0] = mContext;
            View result = root;

            try {
                // Look for the root node.
                int type;
                
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值