[Android] CheckBox:チェックボックスを表示する

チェックボックスとは、いくつかある項目から複数を選択する時に使われるコンポーネントです。ここではチェックボックスの表示方法について説明します。
広 告
目次
前提条件
動作確認端末
- Google Nexus 5 – 5.0.0 – API21(エミュレータ)
1. CheckBoxの概要
チェックボックスを表示させるためにはCheckBoxクラスか<CheckBox>
タグを使います。Button クラスを継承しているため、Buttonクラスのメソッドを使用することが可能です。また<Button>
タグで使える属性も使用することが可能です。
2. チェックボックスを表示する
レイアウトXMLでチェックボックスを表示させるためには、<CheckBox>
タグを使用します。ラベルに表示するテキストはandroid:text
属性で指定します。
<CheckBox>
タグの使用例は以下のとおりです。
res/layout/activity_main.xml
<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"> <!-- @string/checkbox1の参照先は「チェックボックス1」 --> <CheckBox android:id="@+id/checkbox1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/checkbox1" /> <!-- @string/checkbox2の参照先は「チェックボックス2」 --> <CheckBox android:id="@+id/checkbox2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/checkbox2" /> </LinearLayout>
アプリを実行すると以下のようにチェックボックスが画面に表示されます。

Javaコードでチェックボックスを扱うためにはCheckBoxクラスを使用します。ラベルに表示するテキストはsetText()メソッドで設定します。
以下に例を示します。
java/<packagename>/MainActivity.java
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkbox1); checkBox1.setText(getString(R.string.checkbox1)); final CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkbox2); checkBox2.setText(getString(R.string.checkbox2)); } }
res/layout/activity_main.xml
<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"> <CheckBox android:id="@+id/checkbox1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <CheckBox android:id="@+id/checkbox2" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
アプリを実行すると以下のようにチェックボックスが画面に表示されます。
