본문 바로가기
Android/Android Basic

안드로이드 라디오 버튼(RadioButton) 기본

by 수쓰뎁 2023. 1. 14.


1. RadioButton

라디오버튼은 체크박스와 비슷하지만 단일선택만 가능한 기능이다.

중복선택이 불가능하기 때문에 라디오그룹 내의 하나의 라디오버튼을 누르면 나머지 버튼은 자동으로 선택 해제된다.

라디오버튼을 만들기 위해서는 RadioButton 클래스와 RadioGroup 클래스를 사용한다.


2. 라디오버튼 구현

안드로이드 라디오버튼 예제를 만들어보자.

예제는 지난 번 체크박스 예제를 만들 때와 마찬가지로 교통수단 선택 사항으로 버스, 택시, 메트로를 체크박스로 지정하여 선택된 교통수단의 아이콘이 화면에 표시되도록 구현한다.

라디오버튼 예제 테스트를 위해 다음과 같은 순서로 코드를 작성한다.

  • drawable 디렉터리에 교통수단 이미지파일 저장
  • activity_main.xml 작성
  • MainActivity.java 작성

구현하고자 하는 것은 다음과 같다.

  • 라디오버튼을 선택하기 전인 초기화면에서는 교통수단 이미지가 보이지 않도록 한다.
  • 라디오버튼을 선택하면 선택한 라디오버튼에 해당하는 교통수단 이미지를 라디오그룹 하단에 보여준다.

 

1) image 파일 저장

가장 선택된 교통수단의 아이콘은 임의로 만든 이미지 파일을 연결해본다.

연결할 이미지를 프로젝트 디렉터리 창의 res - drawable에 복사한다.

이전의 체크박스 때와 같은 이미지파일을 사용한다.

아이콘으로 사용할 png 파일을 res - drawable 디렉터리로 이동하였다.

 

2) activity_main.xml

다음 작업으로 레이아웃을 구성해보자.

리니어 레이아웃을 기본으로하여 레이아웃을 작성한다.

레이아웃에 사용하는 위젯으로 <RadioButton>, <RadioGroup>, <ImageView>를 사용한다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:text="교통수단 선택"
        android:textSize="30sp"
        android:textColor="@color/black"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingStart="20dp"
        android:layout_marginBottom="20dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="20dp"
            android:text="첫 번째 교통수단"
            android:textSize="20sp"
            android:textColor="@color/black"/>

        <RadioGroup
            android:id="@+id/rg1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/radiobutton1"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:layout_marginRight="50dp"
                android:text="Bus"
                android:textSize="20sp" />

            <RadioButton
                android:id="@+id/radiobutton2"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:layout_marginRight="50dp"
                android:text="Taxi"
                android:textSize="20sp" />

            <RadioButton
                android:id="@+id/radiobutton3"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:layout_marginRight="50dp"
                android:text="Metro"
                android:textSize="20sp" />
        </RadioGroup>

        <ImageView
            android:id="@+id/iv_icon1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@drawable/icon_bus" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="20dp"
            android:text="두 번째 교통수단"
            android:textSize="20sp"
            android:textColor="@color/black"/>

        <RadioGroup
            android:id="@+id/rg2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/radiobutton4"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:layout_marginRight="50dp"
                android:text="Bus"
                android:textSize="20sp" />

            <RadioButton
                android:id="@+id/radiobutton5"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:layout_marginRight="50dp"
                android:text="Taxi"
                android:textSize="20sp" />

            <RadioButton
                android:id="@+id/radiobutton6"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:layout_marginRight="50dp"
                android:text="Metro"
                android:textSize="20sp" />
        </RadioGroup>

        <ImageView
            android:id="@+id/iv_icon2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@drawable/icon_bus" />

    </LinearLayout>

</LinearLayout>

라디오버튼 예제를 만들기 위해 라디오그룹과 라디오버튼을 작성하고 각각의 id를 부여한다.

레이아웃에는 라디오그룹, 라디오버튼, 이미지뷰를 작성한다.

 

3) MainActivity.java

레이아웃 구성이 완료되었으니 이번에는 자바코드를 작성한다.

다음과 같이 자바코드를 작성한다.

public class MainActivity extends AppCompatActivity {

    private RadioGroup radioGroup1, radioGroup2;
    private RadioButton radioButton1, radioButton2, radioButton3,
            radioButton4, radioButton5, radioButton6;
    private ImageView imageView1, imageView2;

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

        initView();
    }

    private void initView() {
        radioGroup1 = findViewById(R.id.rg1);
        radioGroup2 = findViewById(R.id.rg2);

        radioButton1 = findViewById(R.id.radiobutton1);
        radioButton2 = findViewById(R.id.radiobutton2);
        radioButton3 = findViewById(R.id.radiobutton3);
        radioButton4 = findViewById(R.id.radiobutton4);
        radioButton5 = findViewById(R.id.radiobutton5);
        radioButton6 = findViewById(R.id.radiobutton6);

        imageView1 = findViewById(R.id.iv_icon1);
        imageView2 = findViewById(R.id.iv_icon2);
        imageView1.setVisibility(View.GONE);
        imageView2.setVisibility(View.GONE);

        radioGroup1.setOnCheckedChangeListener(((radioGroup, checkedId) -> {
            if (R.id.radiobutton1 == checkedId) {
                imageView1.setVisibility(View.VISIBLE);
                imageView1.setImageResource(R.drawable.icon_bus);
            } else if (R.id.radiobutton2 == checkedId) {
                imageView1.setImageResource(R.drawable.icon_taxi);
            } else {
                imageView1.setImageResource(R.drawable.icon_metro);
            }
        }));

        radioGroup2.setOnCheckedChangeListener(((radioGroup, checkedId) -> {
            if (R.id.radiobutton4 == checkedId) {
                imageView2.setVisibility(View.VISIBLE);
                imageView2.setImageResource(R.drawable.icon_bus);
            } else if (R.id.radiobutton5 == checkedId) {
                imageView2.setImageResource(R.drawable.icon_taxi);
            } else {
                imageView2.setImageResource(R.drawable.icon_metro);
            }
        }));
    }
}

화면을 초기화하기 위해 initView() 메서드를 만들고 그 안에 이미지뷰와 라디오버튼의 내용들을 작성한다.

모두 작성했다면 완성된 코드를 실행해보자.


3. 실행 결과

작성한 라디오버튼 테스트 앱을 실행해보면 다음과 같이 구동되는 것을 확인할 수 있다.

구현하고자 했던대로 라디오버튼을 선택하기 전인 초기화면에서는 교통수단 이미지가 보이지 않는다.

라디오버튼을 선택하면 선택한 버튼에 해당하는 교통수단 이미지를 라디오그룹 하단에 보여지는 것을 확인할 수 있다.

반응형

댓글