关于Recyclerview的一些常见问题

来源:互联网 发布:淘宝破零方法 编辑:程序博客网 时间:2024/05/19 13:23

在android开发中刷新控件必不可少,关于刷新目前常用的用listview,recyclerview。今天重点讲后者,因为recyclerview种种优势,很多开发者纷纷投入使用rv。


但是我要说的是rv虽然比lv好用但是也有很多自身的bug导致开发者在开发过程中头疼不已。

情况一:服务端响应成功但响应实体是没有的,这个时候rv就抽风了,具体异常不好意思给忘了(此处省略),具体解决方式就是在你自定义的rv中你会给rv设置这样一段话
XLayoutManager gridLayoutManager = new XLayoutManager(context, 1);
setLayoutManager(gridLayoutManager);

这里的XLayoutManager 我是继承GridLayoutManager,当然如果你是继承LinearLayout的话也是一样,只是在内部稍作调整

public class XLayoutManager extends GridLayoutManager {

public XLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {    super(context, attrs, defStyleAttr, defStyleRes);}public XLayoutManager(Context context, int spanCount) {    super(context, spanCount);}public XLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) {    super(context, spanCount, orientation, reverseLayout);}@Overridepublic void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {    try {        super.onLayoutChildren(recycler, state);    } catch (IndexOutOfBoundsException e) {        e.printStackTrace();    }}

}

最核心的就是要重写onLayoutChildren这个方法,原因就是当rv进行填充数据时发现数据源是null,造成adapter报IndexOutOfBoundsException异常,重写这个方法也就是在代码中把这个异常捕获到但是并不影响程序的执行这点和IO操作中EOFException是一样的,EOFException是在读取资源时找不到资源标记,导致读取结束之后无法返回 -1这个值,不扯淡了,下一个话题

情况2:rv频繁刷新报java.lang.IllegalArgumentException: Scrapped or attached views may not be recycled
出现这种情况原因就是rv频繁数据操作而adapter刷新又不及时导致data与rv脱离

解决方式:数据源操作之后必须调用adapter.notifyDataSetChanged();数据源操作要和adapter刷新保持一致

最后关于rv的坑肯定不止这些,小伙伴们加油

原创粉丝点击