iT邦幫忙

2025 iThome 鐵人賽

DAY 17
0

今天來介紹CheckBox,那我們就開始吧.w.

什麼是 CheckBox?

CheckBox 是 Android UI 元件中的一種按鈕,有兩種狀態:勾選和未勾選。它通常用於讓使用者從多個選項中進行單一或多重選擇,例如在設定頁面中啟用或停用某些功能,或在問卷中選擇多個興趣愛好

在 XML 中建立 CheckBox

你可以在Layout XML檔案中直接宣告CheckBox

基本語法:

<CheckBox
    android:id="@+id/checkbox_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="選項文字"
    android:checked="false" />

常用語法:

屬性 說明
android:text 設定顯示在 CheckBox 旁邊的標籤文字
android:checked 設定 CheckBox 的預設狀態,true 為勾選,false 為未勾選
android:onClick 可以直接在 XML 中指定一個點擊事件的處理方法名稱(也可以在java內處理)

在 Java 中監聽 CheckBox 狀態

要處理 CheckBox 的點擊事件並獲取其狀態,常見的方法是使用 setOnCheckedChangeListener

核心步驟:

  1. onCreate() 方法中,透過 findViewById() 取得 CheckBox 物件

  2. CheckBox 物件設定一個 OnCheckedChangeListener

  3. 在監聽器的 onCheckedChanged() 方法中編寫邏輯。這個方法會在 CheckBox 的勾選狀態改變時被觸發

    onCheckedChanged(CompoundButton buttonView, boolean isChecked)

    • buttonView: 指的是狀態發生改變的 CompoundButton,也就是你操作的那個 CheckBox
    • isChecked: 一個布林值,true 表示 CheckBox 現在是勾選狀態,false 表示是未勾選狀態

程式碼控制勾選狀態

除了使用者點擊,你也可以在 Java 程式碼中動態設定 CheckBox 的勾選狀態

  • setChecked(boolean checked): 設定 CheckBox 的狀態

    //將checkBoxMusic 設為勾選狀態
    checkBoxMusic.setChecked(true);
    
  • isChecked(): 檢查 CheckBox 目前是否被勾選

    //判斷checkBoxSports 是否被勾選
    if (checkBoxSports.isChecked()) {
        //執行操作...
    }
    
  • toggle(): 反轉目前的狀態(勾選變未勾選,未勾選變勾選)

    //反轉checkBoxMusic的狀態
    checkBoxMusic.toggle();
    

範例

假設你的 activity_main.xml 中有兩個 CheckBox 和一個 Button

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="選擇你的興趣:"
        android:textSize="18sp"/>

    <CheckBox
        android:id="@+id/checkbox_music"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="音樂" />

    <CheckBox
        android:id="@+id/checkbox_sports"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="運動" />

    <Button
        android:id="@+id/submit_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="提交" />

</LinearLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private CheckBox checkBoxMusic, checkBoxSports;
    private Button submitButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //獲取實例
        checkBoxMusic = findViewById(R.id.checkbox_music);
        checkBoxSports = findViewById(R.id.checkbox_sports);
        submitButton = findViewById(R.id.submit_button);

        //監聽器
        checkBoxMusic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String message = isChecked ? "你勾選了音樂" : "你取消了音樂";
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });
        //運動改幾個地方就行了

        //按鈕的點擊事件
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StringBuilder result = new StringBuilder();
                result.append("你選擇了: ");
                
                //檢查Music CheckBox是否被勾選
                if (checkBoxMusic.isChecked()) {
                    result.append("音樂 ");
                }
                
                //檢查Sports CheckBox是否被勾選
                if (checkBoxSports.isChecked()) {
                    result.append("運動");
                }
                
                //如果都沒有選擇
                if (!checkBoxMusic.isChecked() && !checkBoxSports.isChecked()){
                    result.append("無");
                }

                Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
            }
        });
    }
}

CheckBox就先到這裡了,明天會來介紹比較重要一點的RecyclerView,明天見(⁰▿⁰)

https://ithelp.ithome.com.tw/upload/images/20251001/20176154X3voF9ff5l.png


上一篇
Day16 Toast介紹
下一篇
Day18 RecyclerView介紹1
系列文
Android 菜鳥30天從0到1的學習紀錄18
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言