Tips

CheckBox

CheckBoxはアイテムの選択状態をON/OFFで表示することのできるウィジェットです。
 java.lang.Object
 →android.view.View
 →android.widget.TextView
 →android.widget.Button
 →android.widget.CompoundButton
 →android.widget.CheckBox

クラスの定義は上記のようになっており、CheckBoxはCompoundButtonクラスのサブクラスとなります。下記コードはCheckBoxの状態を、Toast内に表示するというものです。

レイアウトxmlファイル

1
2
3
4
5
6
7
8
<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:text="CheckBox" />

javaファイル

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.example.checkbox;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);
        checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
 
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this, "選択しました。",
                                    Toast.LENGTH_SHORT).show();
 
                } else {
                    Toast.makeText(MainActivity.this, "選択を解除しました。",
                                    Toast.LENGTH_SHORT).show();
 
                }
            }
        });
 
    }
}

CheckBoxで用いるonCheckedChanged()の引数は以下の2つです。

  1. buttonView:実際にクリックしたCompoundButtonオブジェクト
    (この例ではCheckBoxオブジェクトとなります。)
  2. checkedId:選択されたCheckBoxのON/OFFの状態を表すID

RadioButtonとの違いはcheckedIdのデータ型です。
RadioButtonではint型(ウィジェットのID)でしたが、CheckBoxではboolean型(true(チェックをした)/false(チェックを外した))となります。

Androidアプリ開発の必須知識!JAVAプログラミングを学べる連載リンク

はじめてのJAVA 連載

Android ユーザーインターフェース応用 ウィジェット TextView,EditText 【Android Tips】
Androidアプリの4大要素とインテント Activity 【Android Tips】
一覧へ戻る

Recent News

Recent Tips

Tag Search