Androidプログラマへの道 〜 Moonlight 明日香 〜 - チェックボックスを作成する
チェックボックスを作成する方法は2通りある.
静的に決定しているものはXMLで定義して, 動的に決定するものはコードで定義するというのが一般的である.



XMLファイルにより定義

res/values/strings.xml
  • チェックボックスに表示する文字列を定義する.
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">チェックボックスを作成する</string>
  <string name="checkbox_label">チェックボックス</string>
</resources>
  • res/layout/main.xml
    • "@+id/checkbox_id"でプログラムからアクセスするIDを定義する.
    • チェックボックスをどれくらいの大きさで配置するかを指定する.
    • "@string/checkbox_label"で表示する文字列を指定する.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <CheckBox android:id="@+id/checkbox_id"
    android:layout_width="wrap_content" ---- 幅
    android:layout_height="wrap_content" ---- 高さ
    android:text= "@string/checkbox_label" ---- 文字列
  </>
</LinearLayout>

コードにより定義

Activity#onCreateメソッドをオーバーライドして, チェックボックスを定義するコードを記述する.
    • CheckBoxクラスとLinearLayoutクラスをインポートする.
    • チェックボックスを生成し, 表示する文字列をセットする.
    • チェックボックスを配置するレイアウトを生成し, チェックボックスをレイアウトに追加する. このとき, チェックボックスをどれくらいの大きさで配置するかを指定する.
    • setContentViewメソッドに, UIツリーのルートノードを表すウィジェットとしてレイアウトを渡して, アクティビティに関連付ける.
package com.moonlight_aska.android.checkbox01;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.LinearLayout;

public class Example02 extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // チェックボックスを生成
    CheckBox chkbox = new CheckBox(this);
    chkbox.setText("チェックボックス");
    // レイアウトにチェックボックスを追加
    LinearLayout layout = new LinearLayout(this);
    layout.addView(chkbox, new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT,
      LinearLayout.LayoutParams.WRAP_CONTENT));

    setContentView(layout);
  }
}