Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android UI 控件學習筆記(二):從清單檔到常用表單控件

編輯:關於 Android 程式設計

寫 Android 的第一道門檻,往往不是語法,而是「畫面怎麼擺」。這一篇就從工程裡最關鍵的兩個檔案說起,再逐一認識登入、註冊這類表單頁最常出現的基礎控件,最後用一個能跑起來的小例子把它們串起來。

一、AndroidManifest.xml:App 的身分證

每個工程的根目錄都有一份 AndroidManifest.xml,它負責宣告兩件新手最容易忽略的事。

1. 權限申請
相機、網路、讀寫外部儲存、定位這類敏感能力,都必須先在清單檔中登記,使用時系統才會放行。少了這一步,程式碼寫得再漂亮也只會拿到一個安全例外。

2. 啟動入口
哪一個 Activity 是使用者點桌面圖示後看到的第一個畫面?答案寫在 intent-filter 裡:加上 MAIN 的 action,再配上 category.LAUNCHER 這個 category,系統啟動器就會把它當成可點擊的入口。

清單檔改完之後,接著要讓它「同步」到建置流程中,Android Studio 才會把新的權限與元件註冊打包進 APK。這個動作在舊版 ADT 時代尤其關鍵,現在多數會自動完成,但觀念要清楚:清單檔不是註解,它會實際改變 App 的能力邊界。

二、畫面從哪裡來:程式碼 + 資源

Android 的 UI 走的是「宣告式描述 + 程式式控制」的雙軌路線:外觀交給 res/layout 底下的 XML 描述,行為交給 Java 程式碼。圖片、字串、色碼、尺寸這些素材則另外收在 res 對應的目錄裡,透過資源 ID 被引用。理解這個分工,後面看任何範例都不會迷路。

三、先認人:表單頁常見的基礎控件

  • TextView:純文字顯示,是所有控件的文字基礎。
  • EditText:可輸入的文本框,TextView 的子類。
  • Button:按鈕,最直白的觸發元件。
  • RadioButton / RadioGroup:單選鈕與它的容器,同組內只能有一個被選中。
  • CheckBox:多選框,彼此獨立,可同時勾選多項。
  • ImageView:圖片控件,靠 src 指定圖源,靠 scaleType 決定縮放策略。

四、兩個最常被寫錯的屬性

關於寬高,正確的說法是这样的:match_parent 是「撐滿父容器」,wrap_content 是「由內容大小決定」,另外還可以直接給固定的 dp 值。很多教學把 wrap_content 寫成「匹配螢幕」,其實並不準確。

另一個是對齊: android:gravity 管的是「控件內部內容」的對齊方式,例如讓文字在框內水平居中;android:layout_gravity 才是「控件本身在父容器裡」的位置。而且在 RelativeLayout 中,layout_gravity 是不生效的——它只在 LinearLayout、FrameLayout 這類容器裡有意義。

五、TextView 與 EditText 的常用屬性

TextView 你只要記住三個:text 決定文字內容、textColor 決定顏色、textSize 決定字級(記得帶 sp 單位,才會跟著系統字級縮放)。

EditText 在此之上多了幾個實用選項:inputType 決定輸入法形態(textPassword 變密碼、number 變數字鍵盤)、hint 是未輸入時的灰色提示文字、drawableLeft 可以在文字左側放圖示、drawablePadding 則控制圖示與文字之間的間距。另外 maxlength 可以限制字數,密碼欄很常用。

六、動手做:同一個畫面的三種寫法

版本一:RelativeLayout 版登入頁

相對布局的精髓是「元件之間互相定位」:alignParentStart、layout_below、layout_toEndOf、layout_centerVertical 這幾個屬性一搭,就能畫出任何拼圖式的畫面。下面的例子做了一個帳號、密碼、性別單選、興趣多選、頭像與登入/取消按鈕的組合:

RelativeLayout
  layout_width / layout_height = match_parent
  paddingLeft / paddingRight = activity_horizontal_margin
  paddingTop / paddingBottom = activity_vertical_margin

  TextView  id=textView
    layout_width=300dp  layout_height=50dp  gravity=center
    text=@string/test  textColor=#4f62f4  textSize=30sp
    alignParentStart + alignParentTop

  EditText  id=editText  hint=請輸入用戶名
    drawableLeft=@mipmap/ic_launcher  drawablePadding=20dp
    layout_width=match_parent  layout_height=50dp
    layout_above=editText2  alignParentStart

  EditText  id=editText2  hint=請輸入密碼
    inputType=textPassword  maxLength=12
    alignParentStart + layout_centerVertical

  RadioGroup  id=rg  orientation=vertical  layout_below=editText2
    RadioButton id=nan  text=男  checked=true
    RadioButton id=nv   text=女  layout_toEndOf=nan

  CheckBox  id=ch01  text=運動
  CheckBox  id=ch02  text=音樂  layout_below=ch01
  CheckBox  id=ch03  text=Android  checked=true

  ImageView  src=@mipmap/zyf  layout_width=match_parent
    layout_height=200dp  layout_below=textView  layout_above=editText
    (若想讓圖片填滿並裁切,可加 scaleType=centerCrop)

  Button  id=btLogin   text=登陸  alignParentBottom + layout_toEndOf=rg
  Button  id=btLogin2  text=取消  alignParentBottom + layout_alignEnd=textView

要留意的是,RelativeLayout 裡每多一個元件,就多一層定位約束,畫面一複雜就難維護。這時候可以換個思路。

版本二:LinearLayout 版登入頁

線性布局靠一句 orientation 決定排列方向,再用 layout_weight 分配剩餘空間。把兩個按鈕包進一個 horizontal 的 LinearLayout、各給 weight=1,就能自動等寬並排,完全不必算座標——這是它相對 RelativeLayout 的最大優勢。

LinearLayout  orientation=vertical
  TextView   text=@string/test  textColor=#ff8543  textSize=25sp
  EditText   hint=請輸入用戶名  drawableLeft=@mipmap/ic_launcher
  EditText   hint=請輸入密碼  inputType=textPassword
  LinearLayout  orientation=horizontal
    Button   text=登陸  layout_weight=1
    Button   text=取消  layout_weight=1
  LinearLayout  orientation=horizontal
    RadioGroup  orientation=horizontal
      RadioButton  text=男
      RadioButton  text=女

這裡有個常見的觀念陷阱:在 LinearLayout 中,同一組 RadioGroup 裡的單選鈕應該只留一個 checked=true。若男女都被標成選中,實際顯示結果會依系統判定而定,邏輯上就已經錯了。

版本三:註冊表單

把上面的技巧疊起來,就得到一個更完整的註冊頁:帳號、密碼、確認密碼三段輸入,左側放性別單選與技能多選,右側放一張 200dp 的頭像,底部一個註冊鈕。這裡刻意用「外層 vertical、內層 horizontal 各佔一半」的巢狀結構,示範如何在不寫死座標的情況下做出左右分欄。

LinearLayout  orientation=vertical
  TextView  文字=用戶名        → EditText id=user  hint=請輸入用戶名
  TextView  文字=密碼          → EditText id=psw   inputType=textPassword
  TextView  文字=請再次輸入密碼 → EditText         inputType=textPassword

  LinearLayout  orientation=horizontal
    LinearLayout  weight=1  orientation=vertical
      TextView=性別
      RadioGroup id=rg  orientation=horizontal
        RadioButton id=nan  text=男  checked=true
        RadioButton id=nv   text=女
      TextView=我的技能有
      CheckBox id=ch01  text=JAVA      checked=true
      CheckBox         text=IOS
      CheckBox         text=Android   checked=true
    LinearLayout  weight=1
      ImageView id=ttpp  200dp x 200dp

  LinearLayout  gravity=center
    Button  id=regt  text=注冊  layout_width=300dp

七、讓控件活起來:監聽器與 Toast

布局只是骨架,互動要靠監聽器。在 MainActivity 裡,先用 setContentView 綁定布局,再用 findViewById 依 ID 抓出控件,最後掛上對應的監聽:

setContentView(R.layout.activity_main3);

Button bt     = (Button) findViewById(R.id.regt);
EditText user = (EditText) findViewById(R.id.user);
RadioGroup rg = (RadioGroup) findViewById(R.id.rg);
ImageView iv  = (ImageView) findViewById(R.id.ttpp);
CheckBox cb   = (CheckBox) findViewById(R.id.ch01);

// 按鈕點擊:把輸入框內容用 Toast 彈出來
bt.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, user.getText(),
                       Toast.LENGTH_SHORT).show();
    }
});

// 單選變化:依選項切換頭像
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.nan) {
            iv.setImageResource(R.mipmap.zz);
        } else {
            iv.setImageResource(R.mipmap.zyf);
        }
    }
});

// 多選變化:勾選時提示選了什麼
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            Toast.makeText(getBaseContext(), "你選擇了" + cb.getText(),
                           Toast.LENGTH_SHORT).show();
        }
    }
});

三個監聽器的分工很值得記住:Button 用 OnClickListener;RadioGroup 用 OnCheckedChangeListener,回呼帶的是「被選中的子控件 ID」,因此判斷男女只要比對 R.id.nan 即可;CheckBox 則用 CompoundButton.OnCheckedChangeListener,回呼帶的是布林值,能直接知道勾選還是被取消。

小結

這一節的三個版本其實是同一個需求的漸進演化:RelativeLayout 適合拼圖式畫面但約束繁瑣,LinearLayout 適合清單式排列且靠 weight 就能等分,兩者搭配才是多數頁面的真實寫法。控件本身反而不難,難的是把「哪個屬性作用在誰身上」想清楚——gravity 與 layout_gravity、match_parent 與 wrap_content,這兩組觀念釐清之後,UI 的學習就只剩下熟練度而已。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved