Android 单选按钮和单选组

Android 单选按钮和单选组,android,kotlin,radio-button,radio-group,Android,Kotlin,Radio Button,Radio Group,我正在开发一个android应用程序,我想编程一个有4个单选按钮的radioGroup。我的目的是检查是否选择了这些单选按钮(知道我一次只能选择一个),并将所选单选按钮的信息保存在变量中。 下面是kotlin中的代码和xml中的代码。由于if上的条件,我无法运行。我正在尝试使用isChecked来验证是否选中了单选按钮 fun button_ConfIniciais(view: View) { val encarregado = "Nome Próprio Apelido"

我正在开发一个android应用程序,我想编程一个有4个单选按钮的radioGroup。我的目的是检查是否选择了这些单选按钮(知道我一次只能选择一个),并将所选单选按钮的信息保存在变量中。 下面是kotlin中的代码和xml中的代码。由于if上的条件,我无法运行。我正在尝试使用isChecked来验证是否选中了单选按钮

    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()
        }

    }
}

在Java中:
int id=radioGroup_Ano.getCheckedRadioButtonId()
在Kotlin中:
val id=radioGroup\u Ano.checkedRadioButtonId

这是检查radiobutton id的方法。
如果要对选中的单选按钮执行特定操作,请执行以下操作:

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 
}

为什么要问一个新用户谷歌这个问题?我在谷歌上搜索了两个多小时,在使用单选组和单选按钮方面几乎找不到可用的Kotlin代码。下面是一些非常完整的代码,展示了如何在Kotlin中使用这两种语言。使用setOnCheckedChangeListener和when语句对输入的数据执行四个数学函数之一。而不是真正优雅的数据输入错误检查。XML代码

<?xml version="1.0" encoding="utf-8"?>
导入android.content.Context 导入android.content.Intent 导入android.support.v7.app.AppActivity 导入android.os.Bundle 导入android.view.view 导入android.widget.Toast 导入kotlinx.android.synthetic.main.activity\u第三页* 导入java.math.RoundingMode 导入java.text.DecimalFormat 导入android.os.CountDownTimer 导入android.widget.RadioButton

类PageThreeActivity:AppCompatActivity(){

var MathFunction:String=“”
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity\u第三页)
rgRadioGroup.setOnCheckedChangeListener({group,checkedId->
如果(检查EDID!=-1){
MathFunction=(findViewById(checkedId)作为单选按钮)。getText().toString()
btnLAMmultiply.setText(MathFunction)
}否则{
MathFunction=“”
btnLAMmultiply.setText(“数学函数”)
}
})
}//结束一次创建
功能(视图:视图){
val id=rgRadioGroup.checkedRadioButtonId
何时(id){
R.id.rbAdd->添加(视图)
R.id.rbSubtract->subtract(视图)
R.id.rbMultiply->multiply(视图)
R.id.rbDivision->division(视图)
else->onLAMmultiply(视图)
}
}
趣味添加(视图:视图){
val X=etValOne.text.toString()
val Y=etValTwo.text.toString()
val multB={X:Double,Y:Double->X.plus(Y)}
val df=十进制(“0.00”)
//val df=十进制(“#.###”)
df.roundingMode=roundingMode.天花
格式(multB(X.toDouble(),Y.toDouble())
setText(df.format(multB(X.toDouble(),Y.toDouble())).toString())
etANS.setText(multB(X.toDouble(),Y.toDouble()).toString())
}
趣味减法(视图:视图){
val X=etValOne.text.toString()
val Y=etValTwo.text.toString()
val multB={X:Double,Y:Double->X.减号(Y)}
val df=十进制(“0.00”)
//val df=十进制(“#.###”)
df.roundingMode=roundingMode.天花
格式(multB(X.toDouble(),Y.toDouble())
setText(df.format(multB(X.toDouble(),Y.toDouble())).toString())
etANS.setText(multB(X.toDouble(),Y.toDouble()).toString())
}
趣味倍增(视图:视图){
val X=etValOne.text.toString()
val Y=etValTwo.text.toString()
val multB={X:Double,Y:Double->X.times(Y)}
val df=十进制(“0.00”)
//val df=十进制(“#.###”)
df.roundingMode=roundingMode.天花
格式(multB(X.toDouble(),Y.toDouble())
setText(df.format(multB(X.toDouble(),Y.toDouble())).toString())
etANS.setText(multB(X.toDouble(),Y.toDouble()).toString())
}
趣味分区(视图:视图){
val X=etValOne.text.toString()
val Y=etValTwo.text.toString()
val multB={X:Double,Y:Double->X.div(Y)}
val df=十进制(“0.00”)
//val df=十进制(“#.###”)
df.roundingMode=roundingMode.天花
格式(multB(X.toDouble(),Y.toDouble())
setText(df.format(multB(X.toDouble(),Y.toDouble())).toString())
etANS.setText(multB(X.toDouble(),Y.toDouble()).toString())
}
仅限乐趣多重(视图:视图){
if(etValOne.text.length==0){
错误(“输入第一个值”)
//toast(“输入第一个值”)
etValOne.requestFocus()
return@onLAMmultiply
}
if(etValTwo.text.length==0){
错误(“输入第二个值”)
//toast(“输入第二个值”)
etValTwo.requestFocus()
return@onLAMmultiply
}
if(rgRadioGroup.checkedRadioButtonId==-1){
错误(“选择函数”)
return@onLAMmultiply
}
DOF功能(视图)
}
有趣的上下文。toast(消息:String){
Toast.makeText(this,message,Toast.LENGTH\u SHORT).show()
}
有趣的错误(消息:字符串){
对象:倒计时(40001000){
覆盖趣味点击(毫秒直到完成:长){
tvrerror.visibility=View.VISIBLE
tveerror.setText(msg)
}
重写函数onFinish(){
tvError.visibility=View.INVISIBLE
tveerror.setText(“”)
}
}.start()
}
有趣的背面(视图:视图){
val intent=intent(this@PageThreeActivity,MainActivity::class.java)
星触觉(意图)
}
//下课
}

你能在谷歌上搜索一下你的问题标题吗?@Khemraj-有一些链接可以找到类似Java的解决方案,但OP正试图在Kotlin中实现这一点。(当然,我所看到的搜索结果也是基于我的搜索历史)如果我们有一个Kotlin答案,那么我们有一个重复的答案。否则,我认为这是一个有效的问题,但我希望看到更多的代码来更好地理解situation@0X0nosugar我已经看过这个问题了。当我发现那个用户想要询问关于无线电组功能的问题时,它在成千上万的链接上得到了解释。所以我不知道
<?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>
package com.androidstackoverflow.learnkotlin
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)
}