首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android ScrollView 中均勻分配多個視圖:修正無效 XML 結構與佈局權重

     編輯:程式設計綜合問答

在 ScrollView 中讓多個視圖垂直均分空間,關鍵在於:ScrollView 只能有一個直接子 View,且內部容器需設置 android:fillViewport="true" 配合 layout_weight。

錯誤 XML 分析

<ScrollView>
    <LinearLayout ...>...</LinearLayout>
</ScrollView>
<LinearLayout>...</LinearLayout> // ❌ ScrollView 後還有同級元素,XML 無效

正確結構

<LinearLayout xmlns:android="..."
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:fillViewport="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <View android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <!-- spacer -->
            <LinearLayout android:id="@+id/moneyWheels" ... />
            <View android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" />
            <LinearLayout android:id="@+id/timeWheels" ... />
            <LinearLayout android:id="@+id/timeWheelsText" ... />
            <View android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" />

        </LinearLayout>
    </ScrollView>

    <com.google.ads.AdView ... /> <-- 底部廣告固定在外層 -->
</LinearLayout>

關鍵點

  • 外層 LinearLayout 垂直排列:ScrollView (weight=1) + 廣告 (wrap_content)。
  • ScrollView 設置 fillViewport="true" 使內部容器至少填滿可視區。
  • 內部容器 LinearLayout 高度 wrap_content,子視圖用 layout_height="0dp" + layout_weight="1" 均分。
  • 間隔用輕量 View 代替 LinearLayout,減少嵌套。

結構正確,權重才能生效,實現真正的均分佈局。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved