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

Android Studio XML 布局報錯 "Not well-formed":標籤前導空格導致解析失敗

     編輯:程式設計綜合問答

錯誤現象

佈局 XML 報錯 `XML: not well-formed`,錯誤指向 `android:layout_alignBottom="@id/input"` 和 `android:layout_below="@id/login_button"` 行。

根本原因

**XML 元素標籤前有空格/縮進字元**。XML 規範要求**標籤名必須緊接 `<` 符號**,不允許前導空白。

錯誤代碼示例


< RelativeLayout ... >  <-- 錯誤:< 和 RelativeLayout 之間有空格
    < ImageView ... />    <-- 錯誤
    < LinearLayout ... >  <-- 錯誤

正確代碼


<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/baidi">

    <ImageView
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:src="@drawable/yezizhi" />

    <LinearLayout
        android:id="@+id/input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/login_button"
        android:layout_marginLeft="28.0dip"
        android:layout_marginRight="28.0dip"
        android:background="@drawable/baidi"
        android:orientation="vertical">
        
        <!-- 子元素 -->
        
    </LinearLayout>

    <Button
        android:id="@+id/buton1"
        android:layout_width="270dp"
        android:layout_height="50dp"
        android:layout_alignBottom="@id/input"
        android:layout_centerHorizontal="true"
        android:background="@drawable/landi"
        android:text="登錄" />

</RelativeLayout>

其他常見 XML 格式錯誤

  • 屬性值未加引號:`android:layout_width=match_parent` → `android:layout_width="match_parent"`
  • 標籤未閉合:`` 缺 `/>` 或 ``
  • 特殊字元未轉義:`&` → `&`、`<` → `<`、`>` → `>`
  • 重複 `id`:`@+id/xxx` 只能出現一次,引用用 `@id/xxx`
  • 引用不存在的 `@id`:`android:layout_below="@id/nonexistent"`

Android Studio 快速修復

  1. **Code → Reformat Code** (Ctrl+Alt+L) 自動格式化,會移除標籤前空格。
  2. **Code → Inspect Code** 全專案掃描 XML 錯誤。
  3. 編輯器左側紅色波浪線滑鼠懸停查看具體錯誤訊息。

結論

XML `not well-formed` 多數由**標籤前導空格、屬性缺引號、標籤未閉合**等語法錯誤引起。**善用 AS 格式化 (Ctrl+Alt+L) 與 Inspect Code**,嚴格遵循 XML 規範:標籤名緊貼 `<`,屬性值加雙引號,標籤正確閉合。

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