標籤:addview match_parent fll_parent 無效 失效
典型錯誤案例:
經常我們會通過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的哦。