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

Android Layout 報錯:You must supply a layout_height attribute 完整解決方案

     編輯:程式設計疑難解答

錯誤現象

在編寫 LinearLayout 嵌套 EditText 與 Button 時,IDE 報錯:#15: You must supply a layout_height attribute。乍看 XML 似乎已給所有視圖設置了 layout_height,為何仍報錯?

代碼排查

原始片段中,外層 LinearLayout 缺少閉合標籤 >,且部分子視圖屬性寫法不規範:

  • android:layout_weight 僅在 LinearLayout 子視圖中生效,但 Button 同時設定了 layout_width 與 layout_weight,易產生歧義;
  • wrap_content 與 match_parent(舊版 fill_parent)混用,API 8+ 建議統一用 match_parent;
  • EditText 缺少 android:hint 或 android:inputType 等常用屬性,雖不直接導致報錯,但屬於最佳實踐缺失。

修正後的完整 XML

<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/LinearLayout2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="${packageName}.${activityClass}">

    <EditText
        android:id="@+id/TitleEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@null" />

    <EditText
        android:id="@+id/ContentEditText"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.86"
        android:ems="10"
        android:hint="@null">
        <requestFocus />
    </EditText>

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

        <Button
            android:id="@+id/AddButton"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="增加" />

        <Button
            android:id="@+id/SearchButton"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="查看" />

    </LinearLayout>
</LinearLayout>

關鍵修正點

  1. 根佈局補全閉合 >,否則解析器會把後續屬性當作文本內容,導致屬性丟失;
  2. 權重佈局規範:使用 layout_weight 時,對應方向的尺寸設為 0dp(垂直用 height,水平用 width),避免「雙重指定」衝突;
  3. 按鈕平均分配:兩個 Button 同設 layout_width="0dp" + layout_weight="1",實現等寬分佈;
  4. 統一尺寸常量:全用 match_parent 替代已棄用的 fill_parent。

避坑指南

  • 檢查 XML 結構完整性:每個標籤必須正確閉合;
  • 使用 IDE 的「Layout Validation」或預覽功能實時發現約束錯誤;
  • 優先使用 ConstraintLayout 替代嵌套 LinearLayout,減少層級與潛在錯誤。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved