RecyclerView crashes when “scrapped or attached views may not be recycled”

前端 未结 27 2628
灰色年华
灰色年华 2020-11-29 19:50

I\'m using a simple implementation of RecyclerView taken from the Android website using a StaggeredGridLayoutManager and I keep getting this error

相关标签:
27条回答
  • 2020-11-29 20:09

    Among the reasons that anyone can face this issue, check if you have set the attribute android:animateLayoutChanges="true"to the RecyclerView. This will cause the recycling and reattaching the RecyclerView's items to fail. Remove it and assign the attribute to the RecyclerView's parent container, such as a LinearLayout/RelativeLayout and you should see the problem go away.

    0 讨论(0)
  • 2020-11-29 20:09

    I too was getting this error whenever i had animateLayoutChanges="true" in layout file for RecyclerView. Delete this attribute and error will disappear!

    0 讨论(0)
  • 2020-11-29 20:10

    Workaround solution if reason of Exception is what itemView has parent. In code, where you have notifyItemRemoved(position), remove itemView from RecyclerView:

    View itemView = mRecyclerView.getLayoutManager().findViewByPosition(position);
    if (itemView != null && itemView.getParent() != null) {
        ((ViewGroup) itemView.getParent()).removeView(itemView);
    }
    notifyItemRemoved(position);
    
    0 讨论(0)
  • 2020-11-29 20:11

    This error is caused if in your XML you have android:animateLayoutChanges set to true and you call notifyDataSetChanged() on the RecyclerView's adapter in the Java code.

    So, just avoid using android:animateLayoutChanges with RecyclerViews.

    0 讨论(0)
  • 2020-11-29 20:11

    In my case it happened because I had a Transition running when trying to resize the RecyclerView because the software keyboard was about to show.

    I fixed it my excluding the RecyclerView from the Transition by using Transition.excludeTarget(R.id.recyclerview, true);

    0 讨论(0)
  • 2020-11-29 20:11

    Let me add another possible fix for this kind of issue, please. I had the same problem with superSlim library for sticky headers in RecyclerView. I used MatrixCursor to set data to RecyclerViewCursorAdapter. The reason for this issue was ID columns equals to 0 for all headers. Hope that would help someone to save couple days of debugging.

    0 讨论(0)
提交回复
热议问题