Android 開發中頻繁查閱的 XML 屬性繁多,本文將高頻屬性按功能分類整理,附帶代碼片段與說明,方便開發者快速查找、複製套用,提升編碼效率。
<string name="password">密\u0020\u0020\u0020\u0020碼</string>
使用 Unicode 轉義 \u0020 代表空格,避免 XML 解析器合併多個空白字元。
<TextView android:singleLine="true" />
<EditText android:singleLine="true" />
現代開發建議改用 android:maxLines="1" 搭配 android:ellipsize="end" 實現單行截斷省略號。
| 屬性 | 值範例 | 作用 |
|---|---|---|
android:password | true | 密碼模式,顯示為圓點/星號 |
android:numeric | integer / signed / decimal | 限制輸入數字類型(API 21+ 建議用 android:inputType="number") |
android:hint | @string/input_pwd | 佔位提示文字,獲得焦點後自動隱藏 |
android:minLength | 5 | 最小輸入長度(需配合程式碼驗證) |
android:maxLength | 10 | 最大輸入長度,超過自動截斷 |
android:visibility="visible" <!-- 預設,顯示並佔據空間 -->
android:visibility="invisible" <!-- 隱藏但保留佈局空間 -->
android:visibility="gone" <!-- 完全移除,不佔空間 -->
android:orientation="vertical" <!-- 垂直排列 -->
android:orientation="horizontal" <!-- 水平排列 -->
<activity android:screenOrientation="portrait" /> <!-- 豎屏 -->
<activity android:screenOrientation="landscape" /> <!-- 橫屏 -->
<!-- 無標題列 -->
android:theme="@android:style/Theme.NoTitleBar"
<!-- 全螢幕(含狀態列)-->
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
布爾類(true/false):
layout_centerHorizontal、layout_centerVertical、layout_centerInParentlayout_alignParentTop/Bottom/Left/Rightlayout_alignWithParentIfMissing引用兄弟元素 ID 類:
layout_above/below/toLeftOf/toRightOflayout_alignTop/Bottom/Left/Right邊距像素類:
layout_marginTop/Bottom/Left/Right (dp/px)android:gravity:控制 View 內容對齊(如文字靠右 gravity="right")android:layout_gravity:控制 View 在父佈局中的位置android:scaleType:ImageView 圖片縮放模式android:layout_weight:LinearLayout 權重分配剩餘空間建議將本文加入書籤,下次查找屬性時直接 Ctrl+F 關鍵字即可秒級定位。