使用 LinearLayout 實作計算器介面,最後一行「0 . =」按鈕排版錯誤。核心問題在於巢狀 LinearLayout 的 layout_weight 分配邏輯誤解:權重值越大佔比越大,但父容器 orientation 決定權重作用方向(水平/垂直)。
<LinearLayout android:orientation="horizontal"> <!-- 外層水平 -->
<LinearLayout android:orientation="vertical" android:layout_weight="3"> <!-- 佔3/4寬度 -->
<LinearLayout android:orientation="horizontal"> ... </LinearLayout> <!-- 0 0 0 -->
<LinearLayout android:orientation="horizontal"> ... </LinearLayout> <!-- 0 . -->
</LinearLayout>
<LinearLayout android:orientation="horizontal" android:layout_weight="1"> <!-- 佔1/4寬度 -->
<Button android:text="=" />
</LinearLayout>
</LinearLayout>
原程式碼內層垂直佈局的按鈕未正確分配寬度/高度,且「0」重複四次、「.」缺失、「=」位置錯誤。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- 左側 3/4:數字鍵區 -->
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:orientation="vertical">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
<Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="1"/>
<Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="2"/>
<Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="3"/>
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
<Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="0"/>
<Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="."/>
<Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text=" "></Button> <!-- 佔位或刪除鍵 -->
</LinearLayout>
</LinearLayout>
<!-- 右側 1/4:等號鍵 -->
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="="/>
</LinearLayout>
LinearLayout 子元素 layout_width="0dp" + layout_weight 分配寬度。LinearLayout 子元素 layout_height="0dp" + layout_weight 分配高度。理解 layout_weight 在巢狀佈局中的傳遞規則,即可精準控制複雜 UI 比例分配。