解决动态添加RadioButton时单选失效问题

在上一篇文章。通过重新测量屏幕宽度和控件宽度,解决了RadioGroup不会换行的问题,这篇文章就说一下动态添加RadioButton时,RadioButton单选失效的问题。
其实很简单,在动态添加的时候给RadioButton设置唯一的id,并且在RadioButton的监听器里实现setTypeface方法即可。直接上代码:

list.forEach {
    
    
            val view = LayoutInflater.from(this).inflate(R.layout.test, null)
            val rbs = view.findViewById<RadioButton>(R.id.rbs)
            //此处的i为给RadioButton添加的唯一id。
            rbs.id = ++i
            rbs.text = it

            rbs.setOnCheckedChangeListener {
    
     buttonView, isChecked ->
                buttonView.setTypeface(null, if (isChecked) Typeface.BOLD else Typeface.NORMAL)

            }
            radioGroup.addView(view)

        }

到此即可实现完毕!

猜你喜欢

转载自blog.csdn.net/lixinxiaos/article/details/103870130