Improve RecyclerView Performance

Are you facing these challenges with your RecyclerView?

1. RecyclerView doesn’t scroll smoothly

2. Some first items scrolled slowly

3. A Horizontal photo slider (like Insta) doesn’t work very well

So let’s start solving the problem

1. RecyclerView initialization

If it is possible to set the width and height of the items at the XML file and they don’t change based on the adapter’s content, add this line to your RecyclerView Initializing method:

recyclerView.setHasFixedSize(true)

By this method, you told RecyclerView to don’t calculate item size every time they were added and removed from RecyclerView.

2. ItemViewCacheSize

recyclerView.setItemViewCacheSize(20)

Set the number of offscreen views to retain before adding them to the potentially shared recycled view pool.

The offscreen view cache stays aware of changes in the attached adapter, allowing a LayoutManager to reuse those views unmodified without needing to return to the adapter to rebind them.

In other words, when you scroll the RecyclerView such that there’s a view that is just barely completely off-screen, the RecyclerView will keep it around so that you can scroll it back into view without having to re-execute onBindViewHolder().

3. setHasStableIds

adapter.setHasStableIds(true)

and in your adapter add this line:

override fun getItemId(position: Int): Long 

{  
return items[position].id.hashCode().toLong()
}

RecyclerView will attempt to synthesize visible structural change events for adapters that report that they have stable IDs when this method is used. This can help for animation and visual object persistence but individual item views will still need to be rebound and relaid out.

These methods help you to improve your RecyclerView performance and maybe they could solve your all problems.

Cheers!!







要查看或添加评论,请登录

Sweta Jain的更多文章

  • Library - SocialView

    Library - SocialView

    Do you know about SocialView? SocialView is a library that is used to implement @mention, #hashtag and hyperlink in a…

社区洞察

其他会员也浏览了