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

Android CheckBox 複選框的用法與監聽處理

編輯:關於 Android 程式設計

CheckBox 是介面開發中最常見的多選控制項。Android 的實作方式很直接:每個 CheckBox 各自掛一個 CompoundButton.OnCheckedChangeListener,在回呼中依 isChecked 決定要加還是要移除。本文用「選擇喜歡的水果」這個例子說明。

程式碼

 package com.zhuguangwei;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

public class ChkBoxActivity extends Activity {

  private TextView myTextView;
  private CheckBox myApple;
  private CheckBox myOrange;
  private CheckBox myBanana;
  private CheckBox myWaterMelon;
  private CheckBox myStrawBerry;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    myTextView = (TextView) findViewById(R.id.myTextView);

    myApple      = (CheckBox) findViewById(R.id.Apple);
    myOrange     = (CheckBox) findViewById(R.id.Orange);
    myBanana     = (CheckBox) findViewById(R.id.banana);
    myWaterMelon = (CheckBox) findViewById(R.id.watermelon);
    myStrawBerry = (CheckBox) findViewById(R.id.strawberry);

    myApple.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
          myTextView.append(myApple.getText().toString());
        } else {
          if (myTextView.getText().toString().contains("蘋果")) {
            myTextView.setText(myTextView.getText().toString().replace("蘋果", ""));
          }
        }
      }
    });

    myOrange.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
          myTextView.append(myOrange.getText().toString());
        } else {
          if (myTextView.getText().toString().contains("橘子")) {
            myTextView.setText(myTextView.getText().toString().replace("橘子", ""));
          }
        }
      }
    });

    myBanana.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
          myTextView.append(myBanana.getText().toString());
        } else {
          if (myTextView.getText().toString().contains("香蕉")) {
            myTextView.setText(myTextView.getText().toString().replace("香蕉", ""));
          }
        }
      }
    });

    myWaterMelon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
          myTextView.append(myWaterMelon.getText().toString());
        } else {
          if (myTextView.getText().toString().contains("西瓜")) {
            myTextView.setText(myTextView.getText().toString().replace("西瓜", ""));
          }
        }
      }
    });

    myStrawBerry.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
          myTextView.append(myStrawBerry.getText().toString());
        } else {
          if (myTextView.getText().toString().contains("草莓")) {
            myTextView.setText(myTextView.getText().toString().replace("草莓", ""));
          }
        }
      }
    });
  }
} 

版面配置

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <TextView
    android:id="@+id/myTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="請選擇一下你喜歡吃的水果:" />

  <CheckBox android:id="@+id/Apple"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:text="蘋果" />

  <CheckBox android:id="@+id/Orange"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:text="橘子" />

  <CheckBox android:id="@+id/banana"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:text="香蕉" />

  <CheckBox android:id="@+id/watermelon"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:text="西瓜" />

  <CheckBox android:id="@+id/strawberry"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:text="草莓" />
</LinearLayout> 

這個寫法可以簡化很多

上面五段程式碼幾乎一模一樣,只差在字串。這種重複在教學範例中很常見,但正式專案應該收斂。有兩個方向:

方向一:共用一個監聽物件

讓 Activity 實作介面,所有 CheckBox 共用同一個回呼,再用 buttonView 參數判斷是誰:

 public class ChkBoxActivity extends Activity
    implements CompoundButton.OnCheckedChangeListener {

  private TextView myTextView;

  @Override
  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    String name = buttonView.getText().toString();
    String current = myTextView.getText().toString();

    if (isChecked) {
      myTextView.setText(current + name);
    } else {
      myTextView.setText(current.replace(name, ""));
    }
  }
}

// 註冊時一次搞定
myApple.setOnCheckedChangeListener(this);
myOrange.setOnCheckedChangeListener(this);
myBanana.setOnCheckedChangeListener(this); 

方向二:不要拿文字當資料

本例把「顯示文字」與「資料值」混在一起用,於是取消勾選時得靠 contains 與 replace 去反推,既脆弱又容易出錯(例如「橘子」與「橘子汽水」會互相干擾)。正確做法是維護一個獨立的狀態集合:

 private final Set<String> selected = new HashSet<>();

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  String key = (String) buttonView.getTag();   // 在 XML 用 android:tag 或程式碼設定
  if (isChecked) {
    selected.add(key);
  } else {
    selected.remove(key);
  }
  myTextView.setText("已選:" + selected.toString());
} 

幾個實務提醒

  • 監聽會在你設定 checked 時觸發。如果在程式碼中呼叫 setChecked(true) 而尚未掛上監聽,順序會影響結果。若要在初始化時設定狀態卻不想觸發回呼,可先暫時移除監聽,設好後再接回。
  • 在 ListView 中使用要小心。因為 convertView 會被回收,若 CheckBox 的狀態存在資料裡,每次 getView 都要重新 setChecked;而 setChecked 又會觸發監聽,容易導致迴圈。實務上會在設定前先 setOnCheckedChangeListener(null)。
  • 樣式客製。android:button 可換成自訂 drawable,android:buttonTint(API 21+)可改勾選色;若想要完全自繪的樣式,可以改用 AppCompatCheckBox 並搭配 buttonTint 的 color selector。
  • 無障礙。CheckBox 的文字標籤要清楚描述選項,因為螢幕閱讀器會直接朗讀它。避免使用「選項一」這種無意義文字。

總結:CheckBox 的技術門檻很低,真正的功夫在狀態管理。把「勾選狀態」存在一個明確的資料結構裡,而不是靠畫面上的文字反推,是新手與資深工程師最明顯的分野之一。

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