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

Android 線性佈局計算器 UI:修正最後一行按鈕錯位與 layout_weight 配置

     編輯:程式設計綜合問答

使用 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」重複四次、「.」缺失、「=」位置錯誤。

修正後的最後一行 XML

<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 分配高度。
  • 權重比例 3:1 表示左側佔 3/4、右側佔 1/4。
  • 按鈕文字修正:1,2,3 / 0,.,(空) / =,符合標準計算器佈局。

理解 layout_weight 在巢狀佈局中的傳遞規則,即可精準控制複雜 UI 比例分配。

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