Android RecyclerView动态addView错乱解决方案

问题

总所周知,RecyclerView上下滑动造成数据错乱是一个非常令人头疼的问题。不仅如此,在RecyclerView中动态addView,也会出现混乱的现象,如下图:

      //RecyclerView中给RadioGroup动态添加RadioButton
       RadioGroup rgEvaluate;
       for (EvaluateItem item : evaluateGroup.getItemList()) {
                    RadioButton itemRB = new RadioButton(mContext);
                    itemRB.setText(item.getItemContent() + "(" + item.getItemScore() + "分)");
                    rgEvaluate.addView(itemRB, LinearLayout.LayoutParams.MATCH_PARENT,
                     LinearLayout.LayoutParams.WRAP_CONTENT);
                }

《Android RecyclerView动态addView错乱解决方案》

解决

其实原理是一样的们都是数据混乱造成的。但是相比于数据混乱,动态addView的解决则方便很多。
只要在添加之前removeAllViews();即可。
如上面代码,修改如下:

RadioGroup rgEvaluate;
rgEvaluate.removeAllViews();//清除全部View
...

原理就是利用清除View的机制,清除滑动过程中数据混乱添加的额外View。

后记

后面有空,会再写一篇详解讲一下RecyclerView滑动时数据混乱的解决方案。

参考

https://blog.csdn.net/u010074743/article/details/54670017

    原文作者:DeMonnnnnn
    原文地址: https://blog.csdn.net/demonliuhui/article/details/83106483
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞