首页 > 解决方案 > 如何使用 kotlin android 扩展从 radiogroup 中检索单选按钮

问题描述

我正在以编程方式从片段中的单选组中添加和删除单选按钮。onCheckedChangeListener 提供对 radiogroup 的引用和选中的单选按钮的整数 id。我可以使用 findViewById 获得对单选按钮的引用,但我可以使用 kotlin android 扩展来做到这一点吗?

class MyFragment: Fragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        radio_group.setOnCheckedChangeListener({ radioGroup: RadioGroup, i: Int ->

            // This may give index out of bounds exception
            someFunction((radioGroup[i-1] as RadioButton).text as String)

            // This works but I don't want to use findViewById
            val rb: RadioButton = radioGroup.findViewById(i) as RadioButton
            onRadioButtonSelect(rb.text as String)            
        })
    }
}

标签: androidkotlinradio-buttonradio-group

解决方案


Kotlin 扩展是编译时的。但是,您希望在运行时找到 id。因此,您将无法使用带有动态添加单选按钮的 kotlin 扩展


推荐阅读