Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

android - "Scrapped or attached views may not be recycled" since support lib 25.0.0

All recyclerviews crashes sometimes, when I scroll the list fast, since I've updated to support lib 25.0.0. There is no layout animator and the everything worked fine, with support lib < 25.

The exception is thrown in the RecyclerView, because holder.itemView.getparent() is not null

    if (holder.isScrap() || holder.itemView.getParent() != null) {
            throw new IllegalArgumentException(
                    "Scrapped or attached views may not be recycled. isScrap:"
                            + holder.isScrap() + " isAttached:"
                            + (holder.itemView.getParent() != null));
        }

Does anyone else experienced that behavior?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To prevent the crash from this issue, you need to call setHasStableIds(boolean) from your adapter and pass the parameter as true:

adapter.setHasStableIds(true);

Explanation: The problem occurs when you call adapter.notifyDataSetChanged();

The recyclerView then calls detachAndScrapAttachedViews(recycler); It temporarily detaches and scraps all currently attached child views. Views will be scrapped into the given Recycler. The Recycler may prefer to reuse scrap views.

Then scrapOrRecycleView(recycler, (int) position, (View) child); is called. This function checks if "hasStableIds" is true or false. If its false then you get the following error :

"Scrapped or attached views may not be recycled."

Stable IDs allow the View (RecyclerView, ListView, etc.) to optimize for the case when items remain the same between notifyDataSetChanged calls. hasStableIds() == true indicates whether the item ids are stable across changes to the underlying data.

If the item ids are stable then it can be reused by the view i.e. "recycled" making the process of re-rendering after the call to notifyDataSetChanged() efficient. If item ids are not stable, there is no guarantee that the item has been recycled as there is no way to track them.

Note: Setting setHasStableIds() to true is not a way to request stable IDs, but to tell Recycler/List/Grid Views that you are providing the said stability.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...