获取RadioGroup中选定的RadioButton的ID

时间:2019-02-03 04:39:51

标签: android kotlin

我有一个RadioGroup,如下:

    <RadioGroup android:layout_width="wrap_content" android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@+id/player_age"
                android:id="@+id/gender"
                android:layout_marginStart="8dp" app:layout_constraintStart_toStartOf="parent"
                android:layout_marginEnd="8dp" app:layout_constraintEnd_toEndOf="parent"
                android:layout_marginTop="18dp">
        <RadioButton
                android:text="Male"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" tools:layout_editor_absoluteY="328dp"
                tools:layout_editor_absoluteX="58dp" android:id="@+id/male"/>
        <RadioButton
                android:text="Female"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" tools:layout_editor_absoluteY="328dp"
                tools:layout_editor_absoluteX="224dp" android:id="@+id/radioButton4"/>
    </RadioGroup>

我浏览了RadioGroup的文档,而getCheckedRadioButtonId似乎是最适合使用的功能:

  

返回该组中所选单选按钮的标识符。   空选择时,返回值为-1。

但是它返回一个无用的Int而不是RadioButton的ID:

    import kotlinx.android.synthetic.main.activity_player_details.*

    override fun onClick(v: View?) {
        val name: String = player_name.text.toString()
        val age: Int = player_age.text.toString().toInt()
        val gender: Int = gender.checkedRadioButtonId
        println(name)
        println(age)
        println(gender) // prints 2131361895
    }
}

有什么主意我该如何检索已检查的id的实际RadioButton

2 个答案:

答案 0 :(得分:0)

在布局文件中,属性android:id="@+id/male"的意思是“使用名为'male'的id常量,如果不存在则创建它”。这导致在R.java int类中生成R.id;如果您查看字段R.id.male的实际值,您会发现它是一个看似随机的数字。

当您从Java代码中使用R.id.male时,实际上您只是在使用一些int值。因此,当您获得选中的ID并进行打印时,就可以看到一个“随机”数字。

但是,您可以使用Resources.getResourceEntryName()方法将数字解析回代表名称的String

val genderId = gender.checkedRadioButtonId // R.id.male, int value 2131361895
val genderString = resources.getResourceEntryName(genderId) // "male"

答案 1 :(得分:0)

  override fun onClick(v: View?) {

       if(radioGroup.getCheckedRadioButtonId() == findViewById(R.id.YOUR_RADIO_BUTTON).getId()) 
       { 
          //TODO  
       }

    val name: String = player_name.text.toString()
    val age: Int = player_age.text.toString().toInt()
    val gender: Int = gender.checkedRadioButtonId
    println(name)
    println(age)
    println(gender) // prints 2131361895
}
}

这行代码将帮助您解决问题。它的作用是getCheckRadioButtonId()返回与您定义的单选按钮关联的ID,并将其与您在 XML 文件中提供的 ID 进行比较。

相关问题