libro
www.tuyano.com
Google androidプログラミング入門

さまざまなGUI部品を使ってみよう! (2/7)

作成:2009-12-28 09:20
更新:2010-05-11 11:16

■ラジオボタンを使う

ラジオボタンは、チェックボックスと似ていますが、ちょっとだけ複雑です。複数のボタンをグループ化して処理しなければならないためです。この点を理解しておく必要があります。

ラジオボタンそのものは「RadioButton」という名前で用意されていますが、これを利用するためには、複数のラジオボタンをグループ化する「RadioGroup」というものを利用する必要があります。この<b[RadioGroupの中にRadioButtonを配置してレイアウトすることで、それらが1つのグループとして機能するようになります。

ボタンの選択状態は、チェックボックスと同様に「getChecked」「setChecked」で操作できますが、「現在、どのラジオボタンが選択されているか」は、RadioGroupに用意されている「getCheckedRadioButtonId」を使います。これにより、現在選択されているラジオボタンのID番号が得られますので、これを元にfindViewByIdでコンポーネントを取得すればいいわけです。

では、以下に簡単な例を挙げておきましょう。起動時に2番目のラジオボタンをチェックしておき、それから現在選択されているラジオボタンを調べてそのラベル(表示されているテキスト)を上に表示させています。

※プログラムリストが表示されない場合

AddBlockなどの広告ブロックツールがONになっていると、プログラムリスト等が表示されない場合があります。これらのツールをOFFにしてみてください。

●プログラム・リスト●

※main.xmlの追加
<RadioGroup
    android:id="@+id/group"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
    
    <RadioButton
        android:text="@string/radio1_label"
        android:id="@+id/radio1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <RadioButton
        android:text="@string/radio2_label"
        android:id="@+id/radio2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    
</RadioGroup>


※string.xmlの追加
<string name="radio1_label">ラジオボタンその1</string>
<string name="radio2_label">ラジオボタンその2</string>


※SampleAppの追加
RadioGroup group = (RadioGroup)this.findViewById(R.id.group);
RadioButton radio1 = (RadioButton)this.findViewById(R.id.radio1);
RadioButton radio2 = (RadioButton)this.findViewById(R.id.radio2);


radio2.setChecked(true);


int selid = group.getCheckedRadioButtonId();
RadioButton selradio = (RadioButton)this.findViewById(selid);
text.setText(selradio.getText());

※関連コンテンツ

「Google androidプログラミング入門」に戻る