match_parent 擠佔空間是元兇將專案導入 Eclipse,XML 佈局預覽或真機執行時,**下方 View 完全不見**,只看得到頂部佈局。
外層或上方佈局設定 android:layout_height="match_parent",導致它**佔滿父容器剩餘所有高度**,擠掉後續兄弟 View。
<!-- 錯誤示範 -->
<LinearLayout android:orientation="vertical" ...>
<View android:layout_height="match_parent" ... /> <!-- 這個把空間全佔了 -->
<View android:layout_height="wrap_content" ... /> <!-- 永遠不會顯示 -->
</LinearLayout>
<!-- 正確示範 -->
<LinearLayout android:orientation="vertical" ...>
<View android:layout_height="wrap_content" ... /> <!-- 內容決定高度 -->
<View android:layout_height="0dp" android:layout_weight="1" /> <!-- 剩餘空間按權重分配 -->
</LinearLayout>
wrap_content:讓 View 依內容高度顯示。layout_weight 分配比例:
<View android:layout_height="0dp" android:layout_weight="1" /> <!-- 佔剩餘 1/2 -->
<View android:layout_height="0dp" android:layout_weight="1" /> <!-- 佔剩餘 1/2 -->
ConstraintLayout(API 9+):以約束鏈接替線性權重,更靈活、扁平化層級。ScrollView 包裹: 若內容超出螢幕,外層需用 ScrollView 或 NestedScrollView,且內部 LinearLayout 高度 wrap_content。android:background="#FF0000" 紅色背景,肉眼確認佔用區域。總結: match_parent 在垂直 LinearLayout 中是「空間霸佔者」。改用 wrap_content 或 layout_weight 即可釋放空間給後續 View。