Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android 常用控制項的 XML 寫法速查

編輯:進階開發

在模擬器上寫 Android 久了,多半都會累積一套自己的速查筆記。以下整理幾個最常用控制項的 XML 寫法,方便實作時直接抄。

按鈕

<Button android:id="@+id/jump"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="button to"
/>

顯示文字

<TextView android:id="@+id/result"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=""
/>

輸入框

<EditText android:id="@+id/height"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:numeric="integer"
    android:text=""
/>

android:numeric="integer" 會限制只能輸入整數並自動帶出數字鍵盤;若需要其他輸入型別,可改用 android:inputType,例如 textPassword、phone、textEmailAddress 等。

單行與多行

<EditText android:id="@+id/text1"
    android:layout_width="200sp"
    android:layout_height="24sp"
    android:text="Text1"
    android:singleLine="True"
/>

<EditText android:id="@+id/text3"
    android:layout_width="180px"
    android:layout_height="80px"
    android:text="Text3"
    android:singleLine="False"
/>

singleLine="True" 強制單行輸入,False 則允許換行成多行。要留意的是,上面範例混用了 sp 與 px:sp 會隨使用者設定的字級縮放,適合文字;px 則是實體像素,在不同解析度的裝置上會呈現不同大小。一般建議改用 dip,讓版面在各尺寸螢幕上保持一致。

幾個通用屬性

  • android:id="@+id/xxx":宣告 ID,之後可用 findViewById 取得該控制項。
  • android:layout_width / layout_height:fill_parent、wrap_content 或明確數值。
  • android:text:顯示文字,正式專案中建議改用 @string/... 抽到 strings.xml,方便日後多語系維護。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved