使用RecyclerView

时间:2016-12-23 11:30:13

标签: android android-recyclerview indexoutofboundsexception linearlayoutmanager

我的申请遇到了问题。我收到了一个 java.lang.IndexOutOfBoundsException:检测到不一致。无效的视图持有者适配器positionViewHolder ,不仅在三星设备上,而且在LG上,因为我已经读过某个地方,这个例外只发生在三星设备上。

我的解决方案是创建自己的LinerLayoutManager并在onLayoutChildren()方法中捕获异常。在实现此解决方案之后,异常不会像以前那样经常发生,但是当我关闭应用程序并在关闭后立即再次启动时,有时仍会发生异常。

有人可以帮我解决这个问题吗?

这是我的LinearLayoutManager

 public class WrapContentLinearLayoutManager extends LinearLayoutManager {


  public WrapContentLinearLayoutManager(Context context) {
    super(context);
 }

  public WrapContentLinearLayoutManager(Context context, AttributeSet attrs,    int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
}

public WrapContentLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
    super(context, orientation, reverseLayout);
}

@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
    try {
        super.onLayoutChildren(recycler, state);
    } catch (IndexOutOfBoundsException e) {
        Timber.e("catching recycler view IndexOutOfBoundsException = " + e);
     }
 }

 @Override
 public boolean supportsPredictiveItemAnimations() {
     return false;
 }
}

MainFragment

    LinearLayoutManager linearLayoutManager = new WrapContentLinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(linearLayoutManager);

堆栈跟踪:

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{27dd5184 position=1 id=-1, oldPos=-1, pLpos:-1 no parent}
at android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:5041)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5172)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5153)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2061)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1445)
 at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1408)
at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1225)
at android.support.v7.widget.LinearLayoutManager.scrollVerticallyBy(LinearLayoutManager.java:1045)
at android.support.v7.widget.RecyclerView$ViewFlinger.run(RecyclerView.java:4579)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

0 个答案:

没有答案