Android RecyclerView動態addView錯亂解決方案
阿新 • • 發佈:2018-11-12
問題
總所周知,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);
}
解決
其實原理是一樣的們都是資料混亂造成的。但是相比於資料混亂,動態addView的解決則方便很多。
只要在新增之前removeAllViews();
如上面程式碼,修改如下:
RadioGroup rgEvaluate;
rgEvaluate.removeAllViews();//清除全部View
...
原理就是利用清除View的機制,清除滑動過程中資料混亂新增的額外View。
後記
後面有空,會再寫一篇詳解講一下RecyclerView滑動時資料混亂的解決方案。