我有一个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>
Run Code Online (Sandbox Code Playgroud)
我已经通过的文档看起来RadioGroup和getCheckedRadioButtonId似乎是最合适的功能使用:
返回该组中所选单选按钮的标识符。空选择时,返回值为 -1。
但是它返回一个无用的Int而不是 id 的RadioButton:
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
}
}
Run Code Online (Sandbox Code Playgroud)
知道如何检索id已检查的实际值RadioButton吗?
在布局文件中,该属性的android:id="@+id/male"意思是“使用id名为‘male’的常量,如果它不存在则创建它”。这会导致int在 R.javaR.id类中生成一个;如果您查看 field 的实际值R.id.male,您会发现它是一些看似随机的数字。
当您使用R.id.malefrom java 代码时,您实际上只是在使用某些int值。因此,当您获得检查的 id 并打印它时,看到一个“随机”数字是有意义的。
但是,您可以String使用以下Resources.getResourceEntryName()方法将数字解析回代表名称的a :
val genderId = gender.checkedRadioButtonId // R.id.male, int value 2131361895
val genderString = resources.getResourceEntryName(genderId) // "male"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3006 次 |
| 最近记录: |