RecyclerView中RadioGroup动态添加RadioButton,在setOnCheckedChangeListener报空异常的问题

报错信息如下:
group.findViewById(checkedId) must not be null

问题分析

RecyclerView中ViewGroup动态添加子View,为了防止位置错乱的发生我们一般都要removeAllViews()。RadioGroup再次显示出来时会由于RecyclerView的复用机制会触发setOnCheckedChangeListener,但是由于我们removeAllViews()移除了所有的子组件,新的RadioButton还没重新add。所以此时group.findViewById(checkedId)必然会报空找不到子组件。

解决方案

在新的RadioButton添加之前,不触发setOnCheckedChangeListener

group.removeAllViews()
group.setOnCheckedChangeListener(null)  

示例代码

override fun onBindViewHolder(holder: ViewHolder, item: ListenerRecommend) {
        holder.itemView.run {
            rgButtons.removeAllViews()
            //添加此句,解决渲染时会触发setOnCheckedChangeListener导致的报错
            rgButtons.setOnCheckedChangeListener(null)
            val itemAdsViewBinder = FragmentListenerItemAdsViewBinder(this@ListenerRecommendViewBinder, fragmentIndexMaiDian)
            multiTypeAdapter.register(FragmentListenerItem::class.java, itemAdsViewBinder)
            recyclerView.adapter = multiTypeAdapter
            recyclerView.setRecycledViewPool(viewPool)
            item.recommendList.forEachIndexed { index, tab ->
                val rb = LayoutInflater.from(context).inflate(R.layout.include_rb_listener_rec, root_view, false) as RadioButton
                rb.text = tab.title
                rb.id = index
                when (tab.title) {
                    context.getString(R.string.ls_xlzh) -> {
                        rb.background = context.getDrawableCompat(R.drawable.check_xlzh)
                    }
                    context.getString(R.string.ls_jyzg) -> {
                        rb.background = context.getDrawableCompat(R.drawable.check_jyzg)
                    }
                    context.getString(R.string.ls_htkd) -> {
                        rb.background = context.getDrawableCompat(R.drawable.check_htkd)
                    }
                    context.getString(R.string.ls_zshg) -> {
                        rb.background = context.getDrawableCompat(R.drawable.check_zshg)
                    }
                }
                if (index == 0) {
                    rb.isChecked = true
                    tv_tip.text = context.getString(R.string.ls_rec_tips, tab.title)
                    topicCategory = context.getString(R.string.ls_rec) + "_" + tab.title
                    setData(tab.title, item)
                }
                rgButtons.addView(rb)
            }
            rgButtons.setOnCheckedChangeListener { group, checkedId ->
                val title = group.findViewById<RadioButton>(checkedId).text.toString()
                tv_tip.text = context.getString(R.string.ls_rec_tips, title)
                topicCategory = context.getString(R.string.ls_rec) + title
                setData(title, item)
            }
        }
    }

你可能感兴趣的:(#,Android,Error笔记)