본문 바로가기
안드로이드 코틀린

[Kotlin][Android] 안드로이드 - Radio Button, Radio Group 사용법

by teamnova 2021. 10. 9.

[Java][Android] 안드로이드 - Radio Button, Radio Group 사용법 (tistory.com)

 

[Java][Android] 안드로이드 - Radio Button, Radio Group 사용법

라디오 버튼이란? 라디오 버튼은 여러 옵션 중 한 가지 옵션을 선택할 수 있도록 만들어주는 뷰입니다. 각 라디오 버튼을 하나의 라디오 그룹(Radio Group)으로 그룹화해줘야 합니다. 만약, 제시할

stickode.tistory.com

 

코틀린 버전의 Radio Button, Radio Group 사용법입니다.

 

라디오 버튼이란? 

라디오 버튼은 여러 옵션 중 한 가지 옵션을 선택할 수 있도록 만들어주는 뷰입니다. 

각 라디오 버튼을 하나의 라디오 그룹(Radio Group)으로 그룹화해줘야 합니다. 

만약, 제시할 옵션을 나란히 표시할 필요가 없다면 스피너(spinner)를 사용해보세요. 

 

https://developer.android.com/guide/topics/ui/controls/radiobutton

 

 

 

라디오 버튼 예시

라디오 버튼은 orientation 속성을 이용하여 horizontal 혹은 vertical로 정렬할 수 있습니다. 

vertical radio group

horizontal radio group

 

 

활용 예제

선택된 라디오 버튼에 따라 TextView에 표시되는 텍스트를 바꾸는 예제를 만들어보겠습니다.

<activity_main.xml>

라디오 버튼 사용을 위해 xml 파일에서 라디오 버튼을 선언해야 합니다.

스틱코드에서 라디오버튼 코드를 즐겨찾기를 누른 뒤, 

xml 파일에서 rad 까지만 입력해도 라디오버튼 및 라디오그룹을 불러낼 수 있는 코드가 나옵니다.

가장 먼저 첫번째 항목을 클릭하여 horizontal radio group을 불러옵니다

xml 파일에 자동으로 Radio Group의 기본 코드가 작성됩니다.

 

그 후, Radio Group 내에 Radio Button을 추가해줍니다. 

이전과 마찬가지로 rad 라고 입력하면 뜨는 항목 중 두번째 항목을 클릭해주세요.

목록 중 두번째 항목을 클릭하면

xml 파일에 자동으로 Radio Button 내용이 입력됩니다.

사용 중인 레이아웃에 맞춰 필요한 부분을 마저 입력해줍니다.

 

또한, 여러개의 항목을 만들어 주기위해 Radio Button을 조금 더 추가해줍니다.

그 후, 선택 값이 띄워질 텍스트뷰와 질문 텍스트뷰를 추가해줍니다.

tex 까지만 입력했을 때 나오는 첫번째 항목을 클릭하면 textview의 기본 내용이 입력됩니다.

텍스트뷰를 추가한 activity_main.xml 의 전체코드입니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/question"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="좋아하는 계절은?"
        app:layout_constraintBottom_toTopOf="@+id/radio_group"
        app:layout_constraintStart_toStartOf="@+id/radio_group" />

    <RadioGroup
        android:id="@+id/radio_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <RadioButton
            android:id="@+id/radio_button_spring"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="봄"
            android:layout_marginEnd="10dp"
            />

        <RadioButton
            android:id="@+id/radio_button_summer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="여름"
            android:layout_marginEnd="10dp" />

        <RadioButton
            android:id="@+id/radio_button_fall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="가을"
            android:layout_marginEnd="10dp" />


        <RadioButton
            android:id="@+id/radio_button_winter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="겨울"
            android:layout_marginEnd="10dp"/>

    </RadioGroup>

    <TextView
        android:id="@+id/selected_season"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:hint="선택된 계절"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/radio_group" />


</androidx.constraintlayout.widget.ConstraintLayout>

여기까진 기존내용과 동일하고 MainActivity.java -> MainActivity.kt 이 부분이 변경됩니다.

 

<MainActivity.kt>

코틀린에서는 각 항목들을 findViewById로 선언 할 필요가 없습니다.

코틀린 익스텐션을 사용하면 id를 바로 코드에서 사용할 수 있습니다.

코틀린 익스텐션의 사용법은

Gradle Script - build.gradle(Module) - plugins 에 id 'kotlin-android-extensions' 추가하시고

오른쪽 위 리로드 버튼 혹은 재빌드 하시면 됩니다.

하지만 코틀린 익스텐션이 deprecated 되면서 앞으로는 뷰바인딩을 사용해야 합니다.

뷰바인딩을 하는 방법에 대해선 다음 포스팅에 작성하도록 하겠습니다.

 

클릭한 radio button에 따라 텍스트를 변경해주기 위해 리스너를 추가합니다.

radio group listener [Kotlin] - Stickode

 

스틱코드

 

stickode.com

클릭되는 값마다 textview 에 다른 값이 출력될 수 있도록 when()을 사용하여 각 라디오 버튼 id에 따라 선택한 계절에 맞는 단어가 출력되도록 코드를 작성해 줍니다.

 

실행화면 입니다

 

MainActivity.kt의 전체코드입니다.

 

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        radio_group.setOnCheckedChangeListener{ group, checkedId ->
            when(checkedId){
                R.id.radio_button_spring -> selected_season.text =  "봄"

                R.id.radio_button_summer -> selected_season.text =  "여름"

                R.id.radio_button_fall -> selected_season.text =  "가을"

                R.id.radio_button_winter -> selected_season.text =  "겨울"
            }
        }


    }
}