Hatena::Groupandroid

組み込みプログラマのAndroid開発覚書

[Ruby] [Android入門] [Android 開発入門] [Android 開発チュートリアル] [逆引きAndroid] [Ruby] [Xperia] [チームらくらく]
 | 

2013-08-21

RadioButtonを使う

16:34

Android studio使用

src/main/java/(中略)/MainActivity

package com.example.radiobuttonsample1;

import android.os.Bundle;
import android.app.Activity;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;


import com.example.radiobuttonsample1.R.id;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RadioGroup radioGroup = (RadioGroup) findViewById(id.radiogroup);
        radioGroup.check(id.radiobutton_green);
        RadioButton radioButton = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = (RadioButton) findViewById(checkedId);
                Toast.makeText(MainActivity.this,
                        "onCheckedChanged():" + radioButton.getText(),
                        Toast.LENGTH_SHORT).show();
            }
        });

    }
   
}

src/main/res/layout/activity_main.xml

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <RadioGroup android:id="@+id/radiogroup"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
        <RadioButton android:id="@+id/radiobutton_red"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:text="Red" />
        <RadioButton android:id="@+id/radiobutton_green"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:text="Green" />
        <RadioButton android:id="@+id/radiobutton_blue"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:text="Blue" />
    </RadioGroup>

</RelativeLayout>

 |