Activity#onCreateメソッドをオーバーライドして, ラジオボタンを定義するコードを記述する.
- LinearLayoutクラス, RadioButtonクラス, RadioGroupクラスをインポートする.
- ラジオボタンを生成し, 表示する文字列をセットする.
- ラジオボタンはチェックなし状態で作成されるので, 通常はどれかをチェックする.
- ラジオグループを生成し, ラジオボタンをグループに追加する.
- ラジオグループを配置するレイアウトを生成し, ラジオグループをレイアウトに追加する. このとき, ラジオグループをどれくらいの大きさで配置するかを指定する.
- setContentViewメソッドに, UIツリーのルートノードを表すウィジェットとしてレイアウトを渡して, アクティビティに関連付ける.
package com.moonlight_aska.android.radiobutton01;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class RadioButton01 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ラジオボタンを生成
RadioButton radio01 = new RadioButton(this);
radio01.setText(R.string.radiobutton_label01);
radio01.setChecked(true); // ラジオボタンをチェック状態に
RadioButton radio02 = new RadioButton(this);
radio02.setText(R.string.radiobutton_label02);
// ラジオボタンをグループ化
RadioGroup group = new RadioGroup(this);
group.addView(radio01);
group.addView(radio02);
// レイアウトにラジオグループを追加
LinearLayout layout = new LinearLayout(this);
layout.addView(group, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
setContentView(layout);
}
}