activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radio Button Example"
android:textAllCaps="true"
android:textStyle="italic"
android:textSize="20sp"
android:textColor="#309"
android:padding="5dp"
android:layout_margin="5dp"
android:id="@+id/tv1"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/rg"
android:orientation="horizontal">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/r1"
android:text="Male"
android:textAllCaps="true"
android:textStyle="italic"
android:textSize="20sp"
android:textColor="#309"
android:padding="5dp"
android:layout_margin="5dp"></RadioButton>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/r2"
android:text="Female"
android:textAllCaps="true"
android:textStyle="italic"
android:textSize="20sp"
android:textColor="#309"
android:padding="5dp"
android:layout_margin="5dp"></RadioButton>
</RadioGroup>
</LinearLayout>
MainActivity.kt
package com.androinidan.radiobutton
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.RadioGroup
import android.widget.RatingBar
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
var radiogroup: RadioGroup?=null
var tv: TextView?=null
@SuppressLint("WrongConstant")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
radiogroup=findViewById(R.id.rg)
tv=findViewById(R.id.tv1)
radiogroup!!.setOnCheckedChangeListener{group, checkedId->
if(checkedId==R.id.r1) {
tv!!.text = ("Male")
Toast.makeText(applicationContext, "You selected Male", Toast.LENGTH_LONG).show()
}
else {
tv!!.text = ("Female")
Toast.makeText(applicationContext, "You selected female", Toast.LENGTH_SHORT).show()
}
}
}
}