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

Android 佈局:子元素重複 xmlns 導致 TextView 置於 Button 後報錯

     編輯:程式設計綜合問答

現象

LinearLayout 中四個 Button 接著一個 TextView,若 TextView 在 Button 之後會崩潰;移到 Button 之前則正常。

根本原因

每個子元素都重複宣告了 xmlns:android="https://schemas.android.com/apk/res/android"。XML 命名空間僅需在**根元素**宣告一次,子元素繼承即可。重複宣告會導致屬性解析錯誤,錯誤位置恰好出現在第一個「多餘命名空間」的元素上,故看似順序問題。

錯誤寫法

<LinearLayout xmlns:android="..." ...>
  <Button xmlns:android="..." ... />   <!-- 錯誤:多餘 xmlns -->
  <Button xmlns:android="..." ... />
  <TextView xmlns:android="..." ... />
</LinearLayout>

正確寫法

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/hud"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#2D4673"
    android:gravity="center"
    android:orientation="horizontal">

  <Button android:id="@+id/b1" android:layout_width="48dp" android:layout_height="48dp" android:text="b1" />
  <Button android:id="@+id/b2" android:layout_width="48dp" android:layout_height="48dp" android:text="b2" />
  <Button android:id="@+id/b3" android:layout_width="48dp" android:layout_height="48dp" android:text="b3" />
  <Button android:id="@+id/b4" android:layout_width="48dp" android:layout_height="48dp" android:text="b4" />
  <TextView android:id="@+id/txt" android:layout_width="match_parent" android:layout_height="48dp"
      android:background="#2D4673" android:textColor="#BCD6E0" android:textSize="36sp" android:typeface="monospace" />
</LinearLayout>

檢查清單

  • 根元素**唯一**宣告 xmlns:android。
  • 子元素**完全移除** xmlns:android。
  • 屬性前綴 android: 保留即可。

補充提示

  • fill_parent 已棄用,改用 match_parent。
  • dp 用於尺寸,sp 用於字體(textSize)。
  • 使用 tools:ignore="MissingPrefix" 可暫時抑制 Lint 警告,但建議徹底修正。

移除多餘命名空間宣告,佈局順序不再影響編譯。

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