核取方塊可讓使用者從一組選項中選取一或多個選項。一般而言,會在垂直清單中提供核取方塊選項。
如要建立各個核取方塊選項,請在版面配置中建立 CheckBox
。由於使用者可從一組核取方塊選項中選取多個項目,而每個核取方塊會分別管理,因此您必須為每個核取方塊註冊一個點擊事件監聽器。
回應點擊事件
請先在清單中使用 CheckBox
物件建立版面配置:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <CheckBox android:id="@+id/checkbox_meat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Meat" /> <CheckBox android:id="@+id/checkbox_cheese" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cheese"/> </LinearLayout>
版面配置準備就緒後,請前往 Activity
或 Fragment
,找到 CheckBox
檢視區塊,然後設定變更事件監聽器,如以下範例所示:
Kotlin
findViewById<CheckBox>(R.id.checkbox_meat) .setOnCheckedChangeListener { buttonView, isChecked -> Log.d("CHECKBOXES", "Meat is checked: $isChecked") } findViewById<CheckBox>(R.id.checkbox_cheese) .setOnCheckedChangeListener { buttonView, isChecked -> Log.d("CHECKBOXES", "Cheese is checked: $isChecked") }
Java
findViewById<CheckBox>(R.id.checkbox_meat) .setOnCheckedChangeListener { buttonView, isChecked -> Log.d("CHECKBOXES", "Meat is checked: $isChecked"); } findViewById<CheckBox>(R.id.checkbox_cheese) .setOnCheckedChangeListener { buttonView, isChecked -> Log.d("CHECKBOXES", "Cheese is checked: $isChecked"); }
先前的程式碼會在每次核取方塊變更狀態時,在 Logcat 中顯示訊息。