在Android中添加N个单选按钮

问题描述

我想基于某个值添加单选按钮。值定义我必须显示的单选按钮的总数。目前,我正在动态添加两个单选按钮,但这对我来说不是添加单选按钮的适当解决方案。如果我必须为此代码显示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 
            }
        }
    }
  • 请注意,必须按照代码中的描述将文本作为数组传递,以满足您的需求