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

Android 常用控制項入門整理:屬性、事件與繼承關係

編輯:關於 Android 程式設計

溫故而知新。以下依據 Android 官方 API,整理一批常用控制項的常見用法(測試環境為 Android 4.4)。

一、TextView

從官方的類別繼承圖可以看到,TextView 繼承 View,直接子類有 Button、CheckedTextView,間接子類則有 AutoCompleteTextView、CheckBox 等。

常見的 XML 屬性:

android:text          TextView 顯示的文字
android:textColor     TextView 文字顏色
android:textAppearance 文字的综合屬性,例如 color、typeface、size、style
android:textStyle     字型樣式(normal 正常、bold 粗體、italic 斜體)
android:textSize      文字大小,建議使用 sp 單位

在 Java 中於 onCreate() 裡設定:

textview = (TextView) findViewById(R.id.textview);
textview.setText("我是TextView嗎?");

二、Button

從圖上可以看出 Button 繼承自 TextView。這裡有個自然的疑問:為什麼 Button 可以設文字,而 ImageButton 不行?先按下,後面再談。

值得一提的是 CompoundButton,它有選定與未選定兩種狀態,是 CheckBox 的父類別。

常見用法:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/self_destruct" />

Button 的關鍵在於監聽器設定,官方範例如下:

public class MyActivity extends Activity {
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.content_layout_id);

        final Button button = (Button) findViewById(R.id.button_id);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // 在這裡處理點擊行為
            }
        });
    }
}

這種逐顆設定的寫法,適合按鈕數量少的情況。當畫面上有十幾顆按鈕時,一個個實作就顯得繁瑣,可以考慮讓 Activity 實作 OnClickListener,再用 switch (v.getId()) 集中處理。

三、ImageButton

注意 ImageButton 的父類是 ImageView,而 Button 的父類是 TextView。前面那個疑問到這裡就解開了:ImageButton 之所以不能設文字,是因為它繼承的 ImageView 裡根本沒有 text 這個屬性,用一句話形容就是「子承父業」。

從視覺呈現的角度,我更偏好 ImageButton——它能用圖片做出精緻的點擊回饋。但 Button 的可擴充性更好,兩者各有適用場景。

常見屬性:

<ImageButton
    android:id="@+id/im_btn2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="@drawable/btn_select" />

這裡的 background 若直接指定一張圖片,ImageButton 是不會有點擊效果的——畢竟它本質上就是個 ImageView。那麼 @drawable/btn_select 從哪來?我們在 res 底下新增一個名為 drawable 的資料夾,再建一個 btn_select.xml:

在 btn_select.xml 中撰寫 selector 規則:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/stop_btn_down"
          android:state_pressed="true" />  <!-- 按下時顯示 -->
    <item android:drawable="@drawable/start_btn_up"
          android:state_pressed="false" /> <!-- 抬起時顯示 -->
</selector>

另一種做法是直接在 Java 中攔截觸碰事件:

img_btn1.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            img_btn1.setImageDrawable(getResources().getDrawable(R.drawable.stop_btn_down));
        } else {
            img_btn1.setImageDrawable(getResources().getDrawable(R.drawable.start_btn_up));
        }
        return false;
    }
});

先不談效能與維護性,光是想到有五顆以上按鈕時要寫五份,就令人卻步。因此建議採用 selector 的做法——宣告式配置永遠比命令式程式碼好維護。

四、ToggleButton

先看效果:

常用屬性:

android:textOn   按鈕被選定時顯示的文字
android:textOff  按鈕未被選定時顯示的文字

Java 實作:

togglebutton = (ToggleButton) findViewById(R.id.toggleButton);
togglebutton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        togglebutton.setChecked(isChecked);
        imageview.setBackgroundColor(isChecked ? Color.BLUE : Color.GREEN);
    }
});

五、ImageView

顯示圖片的控制項,沒有太多需要特別說明的地方。

六、CheckBox

與 ToggleButton 同樣繼承 CompoundButton,屬性也相近。

checkbox = (CheckBox) findViewById(R.id.checkBox);
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Toast.makeText(getApplicationContext(),
                isChecked ? "CheckBox被選中了" : "CheckBox取消了",
                Toast.LENGTH_LONG).show();
    }
});

七、RadioButton

用法與 CheckBox 幾乎相同:

radiobutton = (RadioButton) findViewById(R.id.radioButton);
radiobutton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Toast.makeText(getApplicationContext(),
                isChecked ? "RadioButton被選中了" : "RadioButton取消了",
                Toast.LENGTH_LONG).show();
    }
});

實務上 RadioButton 很少單獨使用,通常會包在 RadioGroup 裡,由群組管理互斥選取。

八、EditText

EditText 繼承 TextView,用來取得使用者輸入的內容。常見屬性:

android:maxLines   輸入框最大行數
android:minLines   輸入框最小行數
android:password   輸入內容是否加密
android:text       預設輸入內容
android:inputType  輸入內容的類型
android:hint       預設提示文字

其中 hint 與 text 的差別值得留意:前者在使用者點擊輸入框後會消失,後者則會保留並讓使用者在其後續輸入。

Java 中常用的取值方式:

editText = (EditText) findViewById(R.id.editText);
editText.getText().toString(); // 取得輸入的字串

九、TimePicker 時間選擇器

從官方說明可以看到它繼承自 FrameLayout,也就是說其內部是以框架布局組成的。TimePicker 可取得小時、分鐘以及 AM/PM。

timepicker = (TimePicker) findViewById(R.id.timePicker1);
timepicker.setIs24HourView(true);  // 12 小時制會顯示 AM/PM,24 小時制則不會
timepicker.getCurrentHour();       // 取得小時,0-23
timepicker.getCurrentMinute();     // 取得分鐘
timepicker.setCurrentHour(12);     // 設定小時
timepicker.setCurrentMinute(12);   // 設定分鐘

timepicker.setOnTimeChangedListener(new OnTimeChangedListener() {
    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
        Toast.makeText(getApplicationContext(),
                "選擇時間是" + hourOfDay + ":" + minute,
                Toast.LENGTH_LONG).show();
    }
});

十、DatePicker 日期選擇器

同樣繼承 FrameLayout。

datePicker = (DatePicker) findViewById(R.id.datePicker);
datePicker.init(2015, 3, 9, new OnDateChangedListener() {
    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        Toast.makeText(getApplicationContext(),
                "選擇時間是" + year + "年" + monthOfYear + "月" + dayOfMonth + "日",
                Toast.LENGTH_LONG).show();
    }
});

注意 init() 的月份參數是從 0 開始計數,傳 3 代表四月而非三月,這裡很容易搞錯。

十一、Spinner 下拉清單

這裡用最簡單的 ArrayAdapter 來綁定資料。

第 1 步:在版面檔中加入 Spinner:

<Spinner
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

第 2 步:建立資料源。在 values 底下新增 array.xml:

<!-- array.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <string-array name="spinner_items">
        <item>上海</item>
        <item>北京</item>
        <item>深圳</item>
    </string-array>
</resources>

第 3 步:在 Activity 中綁定(這裡用系統提供的版面檔,也可以自訂):

spinner = (Spinner) findViewById(R.id.spinner);

// 取得資料源
final String[] items = getResources().getStringArray(R.array.spinner_items);

// 建立 Adapter 並綁定資料源
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
        android.R.layout.simple_spinner_dropdown_item, items);

// 為 Spinner 綁定 Adapter
spinner.setAdapter(adapter);

// 設定監聽
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(getApplicationContext(),
                "選擇的城市是" + items[position],
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) { }
});

十二、SeekBar 拖動條

從類別圖可以看到它繼承自 ProgressBar,外觀也確實相似。

先在版面檔中加入:

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

再在 Java 中監聽三個事件:開始拖動、結束拖動、目前進度(範圍 0 到 100)。

seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        Toast.makeText(getApplicationContext(), "SeekBar END!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        Toast.makeText(getApplicationContext(), "SeekBar Start!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        Toast.makeText(getApplicationContext(), progress + "%", Toast.LENGTH_SHORT).show();
    }
});

十三、Switch

開關型控制項,繼承自 Button 的子類 CompoundButton:

版面檔中加入:

<Switch
    android:id="@+id/switch1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOff="關"
    android:textOn="開" />

Java 中掛上監聽:

switch_btn = (Switch) findViewById(R.id.switch1);
switch_btn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Toast.makeText(getApplicationContext(),
                isChecked ? "Switch打開了" : "Switch關閉了",
                Toast.LENGTH_SHORT).show();
    }
});

整理一下繼承關係

把上面這些控制項的繼承脈絡串起來,其實只有幾條主線:

View → TextView → Button → Switch,同時 Button → CompoundButton → CheckBox / RadioButton / ToggleButton。

View → ImageView → ImageButton。

View → ViewGroup → FrameLayout → TimePicker / DatePicker。

View → ProgressBar → SeekBar。

理解這幾條線之後,查 API 時就有方向:想知道某個控制項能不能設文字,看它繼承鏈上有沒有 TextView 就知道了。

最後補充一點版本面的提醒。本文以 Android 4.4 為基準,其中 getResources().getColor()、getDrawable() 這些不帶 Resources 參數的重載版本在後續版本已標記為 deprecated,建議改用 ContextCompat 的對應方法。另外,若要支援深色模式,直接在程式碼中硬寫 Color.BLUE 這類固定值會顯得突兀,應改為在 res/values 與 res/values-night 中定義色彩資源再以 ContextCompat.getColor() 讀取。

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