본문 바로가기
Android

[Android] RadioGroup, RadioButton 완벽정리

by 유혁. 2017. 8. 7.

Android 에서 자주 사용하는 위젯 중에 하나인 RadioButton에 대하여

 

알아봅시다.

 

RadioButton은 주로 여러종류의 선택항목에서

 

한가지만 선택하는 형태의 버튼입니다.

 

 

[출처] - http://bitsoul.tistory.com/47

 

 

 

6개의 항목중 하나만 선택하는 항목입니다.

 

좋아하는 가수는? 소녀시대 체크하면 됩니다.

 

안드로이드 디바이스에서 RadioButton.isChecked() 메소드를 통해 체크되었는지

 

확인하여 앱을 개발하면 됩니다.

 

 

Difference between RadioGroup and RadioButton?

 

RadioButton은 주로 RadioGroup 내에 존재합니다.

 

라디오 그룹 내의 라디오 버튼이

 

존재하여야 리스트 중 한가지를 선택 할 수 있습니다.

 

 

 

만약 라디오 그룹 내에 라디오 버튼이 존재하지 않는다면?

 

예제를 통해 확인해 봅시다.

 

 

XML 부터 작성해 주세요.

 

activity_main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="vertical"
        android:layout_weight="1">

        <TextView
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Radio Button"
            android:textSize="30dp"/>
        <RadioButton
            android:id="@+id/r_btn1"
            android:text="라디오 버튼1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <RadioButton
            android:id="@+id/r_btn2"
            android:text="라디오 버튼2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">
        <TextView
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="30dp"
            android:text="Radio Group"/>

        <RadioGroup
            android:id="@+id/radioGroup"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <RadioButton
                android:layout_weight="1"
                android:text="라디오 그룹 버튼1"
                android:id="@+id/rg_btn1"
                android:layout_width="0dp"
                android:layout_height="wrap_content" />

            <RadioButton
                android:layout_weight="1"
                android:text="라디오 그룹 버튼2"
                android:id="@+id/rg_btn2"
                android:layout_width="0dp"
                android:layout_height="wrap_content" />

        </RadioGroup>

    </LinearLayout>

</LinearLayout>

 

위 그림과 같은 결과가 나옵니다.

 

상위 2개의 버튼은 단독 라디오 버튼입니다.

 

하위 2개의 버튼은 라디오 그룹 내의 라디오 버튼입니다.

 

라디오 버튼을 단독으로 2개 만들었을 때의 결과는 어떻게될까요?

 

 

 

선택의 개념이 없으므로 2개 모두 중복으로 선택이 가능합니다.

 

라디오 버튼 특성상 메소드 없이 클릭된 버튼을 해제 할 수 없습니다.

 

의미가 없는 버튼이 되어버렸네요

 

 

 

반대로 라디오 그룹 내의 라디오 버튼은

 

두가지 중에 한가지를 선택할 수 있습니다.

 

 

 

1번을 누르고 2번을 누르면 선택이 변화하는 것을 확인 할 수 있습니다.

 

 

결론적으로 라디오 버튼은 라디오 그룹 내에 만들어 주어야 합니다.

 

 

 

 

MainActivity.class (Java)

 

package com.yoohyeok.radiobutton;

import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private RadioButton r_btn1, r_btn2;
    private RadioGroup radioGroup;

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

        
        //라디오 버튼 설정
        r_btn1 = (RadioButton) findViewById(R.id.r_btn1);
        r_btn2 = (RadioButton) findViewById(R.id.r_btn2);
        r_btn1.setOnClickListener(radioButtonClickListener);
        r_btn2.setOnClickListener(radioButtonClickListener);

        //라디오 그룹 설정
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        radioGroup.setOnCheckedChangeListener(radioGroupButtonChangeListener);

    }

    //라디오 버튼 클릭 리스너
    RadioButton.OnClickListener radioButtonClickListener = new RadioButton.OnClickListener(){
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this, "r_btn1 : "+r_btn1.isChecked() + "r_btn2 : " +r_btn2.isChecked() , Toast.LENGTH_SHORT).show();
        }
    };

    //라디오 그룹 클릭 리스너
    RadioGroup.OnCheckedChangeListener radioGroupButtonChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
            if(i == R.id.rg_btn1){
                Toast.makeText(MainActivity.this, "라디오 그룹 버튼1 눌렸습니다.", Toast.LENGTH_SHORT).show();
            }
            else if(i == R.id.rg_btn2){
                Toast.makeText(MainActivity.this, "라디오 그룹 버튼2 눌렸습니다.", Toast.LENGTH_SHORT).show();
            }
        }
    };

}

 

설명은 주석에 있습니다.

 

간단한 소스라 설명이 없이도 이해가 가능하실거라 생각합니다.

 

 

 

AVD로 빌드한 결과입니다.

 

 

잘못된점은 알려주시면 감사하겠습니다.

 

궁금하신건 댓글 남겨주세요~