在 Android 中添加 N 个单选按钮

Add N Number of Radio buttons in Android

我想根据某个值添加单选按钮。值定义了我必须显示的单选按钮的总数。目前我正在动态添加两个单选按钮,但这不是我添加单选按钮的正确解决方案。如果我必须为此代码显示 10 个单选按钮,我必须创建 10 个单选按钮实例。任何人都可以建议我如何实现这一目标。

代码:-

class FragmentQues : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {

    return inflater.inflate(R.layout.fragmentques_layout, container, false)
}

@SuppressLint("ResourceType")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    // Create RadioButton programmatically
    val radioButton1 = RadioButton(activity)
    radioButton1.layoutParams= LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT)
    radioButton1.setText("No")
    radioButton1.id = 1

    val radioButton2 = RadioButton(activity)
    radioButton2.layoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT)
    radioButton2.setText("Yes")
    radioButton2.id = 2

        profile_radio_group.addView(radioButton1)
        profile_radio_group.addView(radioButton2)

        profile_radio_group.setOnCheckedChangeListener { group, checkedId ->

            if (checkedId ==1){
                // Some code 
            }else{
                 // Some code 
            }
        }
}

}

嗯,这可以通过一个简单的 for 循环来完成

class FragmentQues : Fragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        return inflater.inflate(R.layout.fragmentques_layout, container, false)
    }

    @SuppressLint("ResourceType")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val value = 2;
        // If you have custom text for each button you have to define them in a list
        val textList = listOf("No", "Yes")
        
        for(i in 0 until value){
            // Create RadioButton programmatically
            val radioButton = RadioButton(activity)
            radioButton.layoutParams= LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT)

            radioButton.setText(textList[i])
            radioButton.id = i

            profile_radio_group.addView(radioButton)
        }
        

        profile_radio_group.setOnCheckedChangeListener { group, checkedId ->

            if (checkedId ==1){
                // Some code 
            }else{
                // Some code 
            }
        }
    }
  • 请注意,文本必须作为数组传递以满足您在代码中的需求