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

Android CheckBox 勾選框的使用案例解析

編輯:關於 Android 程式設計

CheckBox(勾選框)是多選場景中的常見元件,例如選擇興趣、多選設定等。本文透過一個「興趣選擇」的實際案例,示範如何監聽多個 CheckBox 的勾選狀態並即時回應。

Activity 中的邏輯實作

我們為兩個 CheckBox 分別註冊 setOnCheckedChangeListener 監聽器,並在回呼中依據各自的勾選狀態,組合出對應的顯示文字:

public class MainActivity extends Activity {
    TextView tv;
    CheckBox cb1;
    CheckBox cb2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cb1 = (CheckBox) findViewById(R.id.checkbox1);
        cb2 = (CheckBox) findViewById(R.id.checkbox2);
        tv = (TextView) findViewById(R.id.textview1);
        cb1.setOnCheckedChangeListener(cb);
        cb2.setOnCheckedChangeListener(cb);
    }
    private CheckBox.OnCheckedChangeListener cb = new CheckBox.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            String stv = getString(R.string.hoby);
            String scb1 = getString(R.string.basketball);
            String scb2 = getString(R.string.football);
            if (cb1.isChecked() && cb2.isChecked()) {
                tv.setText(stv + ":" + scb1 + "&&" + scb2);
            } else if (cb1.isChecked() && !cb2.isChecked()) {
                tv.setText(stv + ":" + scb1);
            } else if (!cb1.isChecked() && cb2.isChecked()) {
                tv.setText(stv + ":" + scb2);
            } else {
                tv.setText(stv);
            }
        }
    };
}

關鍵在於兩個 CheckBox 共用同一個監聽器物件 cb,如此一來無論哪個勾選框的狀態改變,都能在 onCheckedChanged 中統一判斷並更新畫面。

對應的佈局檔

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/textview1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hoby" />
    <CheckBox
        android:id="@+id/checkbox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/basketball" />
    <CheckBox
        android:id="@+id/checkbox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/football" />
</LinearLayout>

透過這個案例,你已掌握 CheckBox 多選互動的核心玩法:註冊監聽、讀取狀態、依邏輯組合結果。

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