3.addView調用之後導致子布局的android:layout_width="match_parent"屬性或者 android:layout_width="fll_parent"屬性無效。

來源:互聯網
上載者:User

標籤: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的哦。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.