2

I'm developing an android application and I want to program a radioGroup that has 4 radio buttons. My purpose is to check if these radio buttons have been selected (knowing that I can only select one at a time) and save the information of the selected radio button in a variable. Below is the code in kotlin and the code in xml. I am not able to run because of the condition made on the if. I'm trying to use the isChecked to verify if the radio button is selected.

    fun button_ConfIniciais(view: View) {

    val encarregado = "Nome Próprio Apelido"
    val email = "nomeproprioapelido@hotmail.com"
    val palavrachave = "123"
    val checkedId = radioGroup_Ano.checkedRadioButtonId

    if (Text_Mail.text.isEmpty() &&
            Text_Pass.text.isEmpty() &&
            Text_Enc.text.isEmpty() &&
            Text_ConfPass.text.isEmpty()){

        val builder = AlertDialog.Builder(this@Configuracoes_Iniciais)

        builder.setTitle("Atenção")
        builder.setMessage("Deve preencher todos os campos.")
        builder.setPositiveButton("Continuar") { dialog, which ->
        }

        val dialog: AlertDialog = builder.create()
        dialog.show()
    } else {

        //I want to see if some of the radio button is selected, so I use the isChecked
        if (Text_Mail.text.trim().toString().equals(email) &&
                Text_Pass.text.trim().toString().equals(palavrachave) &&
                Text_Enc.text.trim().toString().equals(encarregado) &&
                Text_ConfPass.text.trim().toString().equals(palavrachave) &&
                 (radioGroup_Ano.radioButton_1.isChecked || 
                            radioGroup_Ano.radioButton_2.isChecked ||
                            radioGroup_Ano.radioButton_3.isChecked || 
                            radioButton_4.isChecked)) {

            val builder = AlertDialog.Builder(this@Configuracoes_Iniciais)

            builder.setTitle("Configurações Iniciais")
            builder.setMessage("Bem-Vindo ao Aprende Comigo! Agora que já configurou os seus dados está pronto para aprender!")
            builder.setPositiveButton("Seguinte") { dialog, which ->
                val it = Intent(this, Bem_Vindo_1::class.java)
                startActivity(it)
            }

            val dialog: AlertDialog = builder.create()
            dialog.show()

        } else {
            val builder = AlertDialog.Builder(this@Configuracoes_Iniciais)

            builder.setTitle("Atenção")
            builder.setMessage("Palavras-chaves não coicidem.")
            builder.setPositiveButton("Continuar") { dialog, which ->
            }

            val dialog: AlertDialog = builder.create()
            dialog.show()
        }

    }
}
Alice
  • 49
  • 1
  • 9
  • 1
    https://www.google.co.in/search?q=radio+button+and+radio+group+in+android&oq=radio+button+and+radio&aqs=chrome.0.0j69i57j69i60j0l3.4959j0j7&sourceid=chrome&ie=UTF-8 – Khemraj Sharma Jul 05 '18 at 16:53
  • 1
    Can you search your question title on google once? – Khemraj Sharma Jul 05 '18 at 16:54
  • 1
    @Khemraj - there are some links which lead to solutions in Java like [this one](https://stackoverflow.com/questions/42502055/how-to-check-which-radio-button-of-a-radio-group-is-selected-android) But OP is trying to do it in Kotlin. (And of course what I see as search results is also based on my search history) If we have a Kotlin answer then we have a duplicate. Else I think this is a valid question but I'd like to see a little more code to better understand the situation – Bö macht Blau Jul 05 '18 at 17:00
  • @Maria - please add some code (maybe with comments where you don't know what to do ) so we can better understand what you're trying to achieve. For example it's different if you only want to get the selected RadioButton at some point or if you want to listen to changes in the checked state. – Bö macht Blau Jul 05 '18 at 17:02
  • 1
    https://www.google.co.in/search?ei=Fk8-W4mfBpi6rQG7t5aIDg&q=radio+group+in+kotlin&oq=radio+group+in+kotlin&gs_l=psy-ab.3..33i160k1l2.32317.34603.0.34860.10.10.0.0.0.0.373.1260.0j3j0j2.5.0....0...1c.1.64.psy-ab..5.5.1259...0j35i39k1j0i67k1j0i20i263k1j33i22i29i30k1.0.4oJnn_Sy0E4 – Khemraj Sharma Jul 05 '18 at 17:03
  • 1
    @0X0nosugar I have read the question. As i got that user want to ask about Radio group functionality that is explained on thousands of links. So i think user should search a bit before raising a question on SO. – Khemraj Sharma Jul 05 '18 at 17:04
  • @Khemraj . good find :D On the one hand I think you're right. On the other hand every time I read some Meta post they seem to want to make Stack Overflow a knowledge repo. So if we don't already have the answer on this site, it is a legit question. And if OP adds some code to illustrate the situation it might make a good question. (And please consider that searching successfully may depend on your search history so if you're a beginner you may not so easily be served what you're looking for) – Bö macht Blau Jul 05 '18 at 17:08
  • @Maria you should show what you have done so far for this problem? So that developers help you solve out your problem. – Khemraj Sharma Jul 05 '18 at 17:12
  • @Khemraj I searched several websites that talked about radio group and radio button however all the solutions that I found or gave errors or were not what I was looking for. Then I asked the question here. – Alice Jul 05 '18 at 17:21
  • @0X0nosugar I edit the question and add some of my latest code – Alice Jul 05 '18 at 17:22
  • @Khemraj all the links that you post I already look in for it – Alice Jul 05 '18 at 17:24
  • Take a look at the answer by @mTak - there is a way to find out if any RadioButton has been checked: the method will return the id of the checked RadioButton if there is any. ["Upon empty selection, the returned value is -1."](https://developer.android.com/reference/android/widget/RadioGroup#getCheckedRadioButtonId()) – Bö macht Blau Jul 05 '18 at 17:30
  • @0X0nosugar but how do I verify that on the if? Put it on a variable? – Alice Jul 05 '18 at 17:35
  • @Maria where exactly do you use the checked radio button. I don't see in your code any usage after retrieving the id. –  Jul 05 '18 at 18:32
  • @mTak - unfortunately OP edited the question to include my suggestions. The retrieved radio button id is compared to -1 in the (currently) second if block – Bö macht Blau Jul 05 '18 at 18:38
  • @0X0nosugar I see that, but is this the only condition needed? I thought that each selection made some difference. –  Jul 05 '18 at 18:40
  • @mTak - After OP added the first batch of code, I could see that this was only about whether was any checked RadioButton at all. You can still see the original version if you click on "edited ... ago". I think it's best if I edit the question to show the original condition – Bö macht Blau Jul 05 '18 at 18:44

3 Answers3

5

In Java: int id = radioGroup_Ano.getCheckedRadioButtonId();
In Kotlin: val id = radioGroup_Ano.checkedRadioButtonId
That's the way to get checked radiobutton's id.
If you want to do something specific for the checked radiobutton, do something like this:

when (id) {
    R.id.radioButton_1 -> your code here
    R.id.radioButton_2 -> your code here
    R.id.radioButton_3 -> your code here
    R.id.radioButton_4 -> your code here
    else -> your code here 
}
3

Why ask a New User to Google the question? I have Google this for the better part of two hours and found little if any usable Kotlin code on using Radio Groups and Radio Buttons. Here is some very complete code that shows how to use both in Kotlin. With a setOnCheckedChangeListener and the when statement to preform one of four math function on entered data. And not real elegant data entry error checking. XML Code

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/tvValOne"
    android:layout_width="180dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginTop="32dp"
    android:paddingBottom="8dp"
    android:paddingRight="16dp"
    android:paddingTop="8dp"
    android:text="Value One"
    android:textAlignment="textEnd"
    android:textColor="@color/color_Black"
    android:textSize="28sp"
    android:textStyle="bold"
    app:layout_constraintEnd_toStartOf="@+id/guideline2"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/tvValTwo"
    android:layout_width="180dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="32dp"
    android:paddingBottom="8dp"
    android:paddingRight="16dp"
    android:paddingTop="8dp"
    android:text="Value Two"
    android:textAlignment="viewEnd"
    android:textColor="@color/color_Black"
    android:textSize="28sp"
    android:textStyle="bold"
    app:layout_constraintEnd_toStartOf="@+id/guideline2"
    app:layout_constraintStart_toStartOf="@+id/tvValOne"
    app:layout_constraintTop_toBottomOf="@+id/tvValOne" />

<TextView
    android:id="@+id/tvANS"
    android:layout_width="180dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginTop="32dp"
    android:paddingBottom="8dp"
    android:paddingRight="16dp"
    android:paddingTop="8dp"
    android:text="Answer"
    android:textAlignment="textEnd"
    android:textColor="@color/color_deepBlue"
    android:textSize="28sp"
    android:textStyle="bold"
    app:layout_constraintEnd_toStartOf="@+id/guideline2"
    app:layout_constraintStart_toStartOf="@+id/tvValTwo"
    app:layout_constraintTop_toBottomOf="@+id/tvValTwo" />

<android.support.constraint.Guideline
    android:id="@+id/guideline2"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.3203125" />

<EditText
    android:id="@+id/etValOne"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="32dp"
    android:ems="10"
    android:inputType="number|numberDecimal"
    android:textColor="@color/color_Black"
    android:textSize="24sp"
    android:textStyle="bold"
    app:layout_constraintStart_toStartOf="@+id/guideline2"
    app:layout_constraintTop_toTopOf="parent" />

<EditText
    android:id="@+id/etValTwo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="32dp"
    android:ems="10"
    android:inputType="number|numberDecimal"
    android:textColor="@color/color_Black"
    android:textSize="24sp"
    android:textStyle="bold"
    app:layout_constraintStart_toStartOf="@+id/guideline2"
    app:layout_constraintTop_toBottomOf="@+id/etValOne" />

<EditText
    android:id="@+id/etANS"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="32dp"
    android:ems="10"
    android:inputType="number|numberDecimal"
    android:textColor="@color/color_Black"
    android:textSize="24sp"
    android:textStyle="bold"
    app:layout_constraintStart_toStartOf="@+id/guideline2"
    app:layout_constraintTop_toBottomOf="@+id/etValTwo" />

<Button
    android:id="@+id/btnLAMmultiply"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="120dp"
    android:onClick="onLAMmultiply"
    android:padding="16dp"
    android:text="Select Function"
    android:textColor="@color/color_Purple"
    android:textSize="24sp"
    android:textStyle="bold"
    app:layout_constraintStart_toStartOf="@+id/guideline2"
    app:layout_constraintTop_toBottomOf="@+id/etANS" />

<Button
    android:id="@+id/btnBack"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="32dp"
    android:layout_marginStart="32dp"
    android:onClick="onBACK"
    android:padding="16dp"
    android:text="BACK"
    android:textColor="@color/color_Purple"
    android:textSize="24sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<TextView
    android:id="@+id/tvError"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="52dp"
    android:layout_marginStart="32dp"
    android:text="TextView"
    android:textColor="@color/color_Red"
    android:textSize="30sp"
    android:textStyle="bold"
    android:visibility="invisible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="@+id/guideline2" />

<RadioGroup
    android:id="@+id/rgRadioGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="32dp"
    android:layout_marginTop="32dp"
    android:orientation="vertical"
    app:layout_constraintStart_toStartOf="@+id/guideline2"
    app:layout_constraintTop_toBottomOf="@+id/btnLAMmultiply" >

    <RadioButton
        android:id="@+id/rbAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Value Addition"
        android:textColor="@color/color_Purple"
        android:textSize="30sp"
        android:textStyle="bold" />

    <RadioButton
        android:id="@+id/rbSubtract"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Value Subtraction"
        android:textColor="@color/color_deepBlue"
        android:textSize="30sp"
        android:textStyle="bold" />

    <RadioButton
        android:id="@+id/rbMultiply"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Value Multiplication"
        android:textColor="@color/color_Red"
        android:textSize="30sp"
        android:textStyle="bold" />

    <RadioButton
        android:id="@+id/rbDivision"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Value Division"
        android:textColor="@color/color_Yellow"
        android:textSize="30sp"
        android:textStyle="bold" />

</RadioGroup>

Now the Activity Code if you are new to Listeners PLEASE understand they are placed in the onCreate method and they sit there and just LISTEN no need to call them

package com.androidstackoverflow.learnkotlin

import android.content.Context import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import kotlinx.android.synthetic.main.activity_page_three.* import java.math.RoundingMode import java.text.DecimalFormat import android.os.CountDownTimer import android.widget.RadioButton

class PageThreeActivity : AppCompatActivity() {

var MathFunction:String = ""

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

    rgRadioGroup.setOnCheckedChangeListener( { group, checkedId ->
        if (checkedId != -1) {
            MathFunction = (findViewById<View>(checkedId) as RadioButton).getText().toString()
            btnLAMmultiply.setText(MathFunction)

        } else {
            MathFunction = ""
            btnLAMmultiply.setText("Math Function")

        }
    })

}// end onCreate


fun doFunction(view: View){

    val id = rgRadioGroup.checkedRadioButtonId

    when (id) {
        R.id.rbAdd -> add(view)
        R.id.rbSubtract -> subtract(view)
        R.id.rbMultiply -> multiply(view)
        R.id.rbDivision ->division(view)
        else -> onLAMmultiply(view)
    }
}

fun add(view: View){

    val X = etValOne.text.toString()
    val Y = etValTwo.text.toString()
    val multB = {X:Double,Y:Double -> X.plus(Y)}
    val df = DecimalFormat("0.00")
    //val df = DecimalFormat("#.##")
    df.roundingMode = RoundingMode.CEILING
    df.format(multB(X.toDouble(),Y.toDouble()))
    etANS.setText(df.format(multB(X.toDouble(),Y.toDouble())).toString())
    etANS.setText(multB(X.toDouble(),Y.toDouble()).toString())
}

fun subtract(view: View){

    val X = etValOne.text.toString()
    val Y = etValTwo.text.toString()
    val multB = {X:Double,Y:Double -> X.minus(Y)}
    val df = DecimalFormat("0.00")
    //val df = DecimalFormat("#.##")
    df.roundingMode = RoundingMode.CEILING
    df.format(multB(X.toDouble(),Y.toDouble()))
    etANS.setText(df.format(multB(X.toDouble(),Y.toDouble())).toString())
    etANS.setText(multB(X.toDouble(),Y.toDouble()).toString())
}

fun multiply(view: View){

    val X = etValOne.text.toString()
    val Y = etValTwo.text.toString()
    val multB = {X:Double,Y:Double -> X.times(Y)}
    val df = DecimalFormat("0.00")
    //val df = DecimalFormat("#.##")
    df.roundingMode = RoundingMode.CEILING
    df.format(multB(X.toDouble(),Y.toDouble()))
    etANS.setText(df.format(multB(X.toDouble(),Y.toDouble())).toString())
    etANS.setText(multB(X.toDouble(),Y.toDouble()).toString())
}

fun division(view: View){

    val X = etValOne.text.toString()
    val Y = etValTwo.text.toString()
    val multB = {X:Double,Y:Double -> X.div(Y)}
    val df = DecimalFormat("0.00")
    //val df = DecimalFormat("#.##")
    df.roundingMode = RoundingMode.CEILING
    df.format(multB(X.toDouble(),Y.toDouble()))
    etANS.setText(df.format(multB(X.toDouble(),Y.toDouble())).toString())
    etANS.setText(multB(X.toDouble(),Y.toDouble()).toString())
}

fun onLAMmultiply(view: View ){

    if(etValOne.text.length == 0){
        error("Enter First Value")
        //toast("Enter First Value")
        etValOne.requestFocus()
        return@onLAMmultiply
    }

    if(etValTwo.text.length == 0){
        error("Enter Second Value")
        //toast("Enter Second Value")
        etValTwo.requestFocus()
        return@onLAMmultiply
    }

    if(rgRadioGroup.checkedRadioButtonId == -1){
        error("SELECT A FUNCTION")
        return@onLAMmultiply
    }

    doFunction(view)
}

fun Context.toast(message: String) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

fun error(msg:String){
    object : CountDownTimer(4000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            tvError.visibility = View.VISIBLE
            tvError.setText(msg)
        }
        override fun onFinish() {
            tvError.visibility = View.INVISIBLE
            tvError.setText("")
        }
    }.start()
}

fun onBACK(view: View){
    val intent = Intent(this@PageThreeActivity,MainActivity::class.java)
    startActivity(intent)
}

// End of Class }

Vector
  • 3,066
  • 5
  • 27
  • 54
  • @Maria We posted a few lines of code on how to use Radio Group and Radio Buttons in Kotlin. Feel free to post a comment if you have other questions about the code – Vector Sep 02 '18 at 23:21
2
radioGroup.setOnCheckedChangeListener { group, i ->
    val selected = this.findViewById(group.checkedRadioButtonId))
}
Hobo Joe
  • 737
  • 1
  • 9
  • 11
  • 2
    This answer could be improved by adding an explanation of why this code works. – jkdev Jul 06 '18 at 00:51
  • While this code snippet may be the solution, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-%E2%80%8C%E2%80%8Bcode-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Narendra Jadhav Jul 06 '18 at 04:44