정보를 보호하는 대학생
<안드로이드 스터디 03> 라디오 버튼을 누르면 토스트 띄우기 본문
1. 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:layout_marginStart="196dp"
android:layout_marginTop="282dp"
android:layout_marginEnd="106dp"
android:layout_marginBottom="305dp"
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/RadioOrange"
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="바나나" />
</RadioGroup>
</androidx.constraintlayout.widget.ConstraintLayout>
2. 코틀린 코드
package com.android.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 RadioOrange : RadioButton
lateinit var RadioBanana : RadioButton
/////////////////////////////////
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
RadioGroup = findViewById(R.id.RadioGroup)
RadioApple = findViewById(R.id.RadioApple)
RadioOrange = findViewById(R.id.RadioOrange)
RadioBanana = findViewById(R.id.RadioOrange)
RadioGroup.setOnCheckedChangeListener{group, checkedId ->
when(checkedId){
R.id.RadioApple -> Toast.makeText(applicationContext, "사과", Toast.LENGTH_SHORT).show()
R.id.RadioOrange ->Toast.makeText(applicationContext, "오렌지", Toast.LENGTH_SHORT).show()
R.id.RadioBanana -> Toast.makeText(applicationContext, "바나나", Toast.LENGTH_SHORT).show()
}
}
}
}
3. 결과화면

4. 하고싶은 말
라디오버튼은 라디오그룹으로 묶어서 사용하는 것을 알게 되었다.
또한 토스트를 띄우는 코드가 체크박스와는 약간 차이가 있다.
'개발 > 안드로이드 스터디' 카테고리의 다른 글
<안드로이드 스터디 06> 색깔 등록, 기본 어플 색깔 설정 바꾸기 (0) | 2022.01.14 |
---|---|
<안드로이드 스터디 05> 체크박스 -> 라디오버튼 -> 버튼 -> 선택에 따른 이미지 보여주기 (0) | 2022.01.14 |
<안드로이드 스터디 04> EditText 입력 후 버튼누르면 그대로 TextView 출력 (0) | 2022.01.07 |
<안드로이드 스터디 02> 체크박스를 누르면 토스트 띄우기 (0) | 2022.01.06 |
<안드로이드 스터디 01> 간단한 계산기 만들기 (0) | 2022.01.06 |