Radio button and radio group using kotlin - Joklinz-Tech

Latest

Home Of Tech news,jobs and android tutorials

Tuesday 13 February 2018

Radio button and radio group using kotlin





Xml

<RadioGroup    android:id="@+id/rg"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:orientation="horizontal"    android:padding="15dp"    >    <RadioButton        android:id="@+id/rb_coldfusion"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Bad"        android:paddingRight="15dp"        />    <RadioButton        android:id="@+id/rb_flex"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Good"        android:paddingRight="15dp"        />
</RadioGroup>

Kotlin code

val rg = findViewById<RadioGroup>(R.id.rg)

        val btn=findViewById<Button>(R.id.button)
        btn.setOnClickListener {
            val selectedRadioButtonID = rg.checkedRadioButtonId

            // If nothing is selected from Radio Group, then it return -1
            if (selectedRadioButtonID != -1) {

                val selectedRadioButton = findViewById<View>(selectedRadioButtonID) as RadioButton
                val selectedRadioButtonText = selectedRadioButton.text.toString()
                Toast.makeText(this,selectedRadioButtonText,Toast.LENGTH_SHORT).show()

            } else {
                Toast.makeText(this,"Nothing selected from Radio Group.",Toast.LENGTH_SHORT).show()

            }


No comments:

Post a Comment