解决 RecyclerView java.lang.IndexOutOfBoundsException

  |   0 评论   |   963 浏览

使用RecyclerView 有时莫名其妙的就报数组越界异常了

1、重写LinearLayoutManager


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

2、设置LayoutManager

  // mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); 
  // 解决RecyclerView可能出现的holder数组越界Bug 
  mRecyclerView.setLayoutManager(
        new WrapContentLinearLayoutManager(this,LinearLayoutManager.VERTICAL, false)); 

>