由于 Kotlin 不支持傳統的 for 回圈,如果 String x 值與 RadioButton 文本匹配,是否有辦法在 RadioGroup 中選擇 RadioButton?
像這樣的東西可以在 Java 上運行,但不能在 Kotlin 中運行
for(i...radioGroup.childCount){
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
}
然后像這個代碼一樣根據字串值選擇正確的收音機
if(radioBtn.text.toString.equals("Sample"))
radioBt.check(R.id.radio1);
else
radioBt.check(R.id.radio2);
uj5u.com熱心網友回復:
rg - 你的電臺組
for (rbPosition in 0 until rg.childCount) {
val rb = rg.getChildAt(rbPosition) as RadioButton
if (rb.text == yourText) {
//do stuff for example rb.isChecked = true
}
}
uj5u.com熱心網友回復:
您可以使用 獲取單選組中的所有單選按鈕radioGroup.children。
你可以像@rost 建議的那樣迭代這個集合。
查找按鈕的一種更實用的方法可以是:
val radioButton = radioGroup.children
.map { it as RadioButton } // Convert the sequence of Views to sequence of RadioButtons
.find { it.text == buttonText }!! // Don't use this !! if there's a possibility that no RadioButton with provided text exists
// Now you have the button, use it however you want
uj5u.com熱心網友回復:
我認為這更好,因為它可能有除 RadioButton 之外的任何視圖。
val radioButton = radioGroup.children.filter {
it is RadioButton && it.text == "YOUR STRING HERE"
}.map {
it as RadioButton
}.firstOrNull()
radioButton?.let {
it.isChecked = true
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/362392.html
標籤:安卓 科特林 android-radiobutton android-radiogroup
上一篇:使用片段導航(導航圖)導航時呼叫目標片段的函式/方法
下一篇:使用視圖模型在片段之間傳遞資料
