Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 動態加入 View 時如何讓 GridView 填滿父容器

編輯:Android 開發實例

需求

希望將 grid.xml 中的 GridView 動態加入 id 為 ContentView 的 LinearLayout,而不是直接寫死在 main.xml 中。這樣做的好處是畫面切換時更靈活,也能依需求動態決定要顯示的內容。

問題現象

如果把 GridView 的 XML 內容直接複製到 main.xml 的 LinearLayout 容器中,畫面顯示正常。但若透過 LayoutInflater 取得 GridView,再用 addView 動態加入,layout_height 設定為 fill_parent 或固定數值都無法讓 GridView 填滿父容器,畫面只會顯示有資料的區塊。

原因分析

動態加入子檢視時,XML 中的 layout 屬性不會自動轉成對應父容器的 LayoutParams。若沒有明確指定 LayoutParams,子 View 就可能無法依照預期填滿父容器。

解法

在呼叫 addView 時,明確建立 LinearLayout.LayoutParams,並將寬高都指定為 FILL_PARENT。

ly.addView(gridview, new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.FILL_PARENT,
    LinearLayout.LayoutParams.FILL_PARENT));

結語

動態加入 View 時,除了 XML 本身的屬性,也要留意父容器型別與 LayoutParams。補上正確的 LayoutParams 後,GridView 就能正常填滿 LinearLayout。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved