解决不论是layoutinflute还是listview的addView调用之后导致子布局的match失效

典型错误案例: 
        经常我们会通过addView方法,动态添加一些子布局,比如下面的一段代码. 
LinearLayout linParent = (LinearLayout) findViewById(R.id.aty_slider_linParent); 
View vChild = mInflater.inflate(R.layout.view_loding, null); 
linParent.addView(vChild); 
        view_loading是一个布局文件: 
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:gravity="center" 
    android:orientation="horizontal" > 
</LinearLayout> 

         按理说,view_loding所属的布局控件会完全填充满linParent的,但是实际的效果与预想不同,只是自适应大小而已。

原因分析: 
         查看addView方法的源码如下 
    public void addView(View child) { 
        addView(child, -1); 
    } 
        再查看addView的另外一个重载方法 
    public void addView(View child, int index) { 
        LayoutParams params = child.getLayoutParams(); 
        if (params == null) { 
            params = generateDefaultLayoutParams(); 
            if (params == null) { 
                throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null"); 
            } 
        } 
        addView(child, index, params); 
    } 
        里面有句话child.getLayoutParams(),而getLayoutParams方法说明中有句话为:This method may return null if this View is not attached to a parent ViewGroup。意思就是如果没有被添加至父控件时,结果是会返回null的,很显然,到目前的代码跟踪情况来看,vChild还没有被添加至linParent,所以会去调用generateDefaultLayoutParams()方法,而generateDefaultLayoutParams的方法实现如下: 
 protected LayoutParams generateDefaultLayoutParams() { 
        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    } 
       所以就很明显的造成了子布局android:layout_width="match_parent"属性失效。 
解决方案: 
        当addView方法完成之后,重新设置子控件vChild的LayoutParams属性即可。 
vChild.setLayoutParams(new android.widget.LinearLayout.LayoutParams( 
android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 
android.widget.LinearLayout.LayoutParams.MATCH_PARENT)); 
        其中的LayoutParams所属类必须为linParent 的类型,否则会有bug的哦。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值