GURU/AndroidStudio

[AndroidStudio] RadioButton

myejinni 2022. 7. 15. 10:41

실습 3-02 : 라디오 버튼을 선택하면 선택된 버튼의 문자열을 토스트 메시지로 보여줌

 

 

<MainActivity.kt>

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    lateinit var radioGroup : RadioGroup
    lateinit var radioApple : RadioButton
    lateinit var radioBanana : RadioButton
    lateinit var radioOrange : RadioButton

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

        radioGroup=findViewById(R.id.radioGroup)
        radioApple=findViewById(R.id.radioApple)
        radioBanana=findViewById(R.id.radioBanana)
        radioOrange=findViewById(R.id.radioOrange)

        radioGroup.setOnCheckedChangeListener{ group, checkedId ->
            when(checkedId){
                R.id.radioApple -> Toast.makeText(applicationContext, "사과", Toast.LENGTH_SHORT).show()
                R.id.radioBanana-> Toast.makeText(applicationContext, "바나나", Toast.LENGTH_SHORT).show()
                R.id.radioOrange -> Toast.makeText(applicationContext, "오렌지", Toast.LENGTH_SHORT).show()

            }
        }
    }
}

 

<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">

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

        <RadioButton
            android:id="@+id/radioApple"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="사과" />

        <RadioButton
            android:id="@+id/radioBanana"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="바나나" />

        <RadioButton
            android:id="@+id/radioOrange"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="오렌지" />
    </RadioGroup>
</androidx.constraintlayout.widget.ConstraintLayout>

 

<AVD 실행 결과>