Updated 29 May 2019
RecyclerView is a flexible view for providing a limited window into a large data set. RecyclerView is an evolutionary version of Listview — one of the most important widgets used in Android development. Android apps using Listview for implementing newsfeed or contact lists will likely face performance issues or unnecessary lags when the user scrolls the view fast. But RecyclerView has improved performance, and it provides a fluid scroll experience for the user.
I will give you the information and important rules you should follow and what you should never do when working with RecyclerView:
1. Replace a complex layout (nested views, RelativeLayout) with the new optimized ConstraintLayout.
ConstraintLayout is to optimize and flatten the view hierarchy of your layouts by applying some rules to each view to avoid nesting.
2. If possible, make all elements of the RecyclerView with the same height. And add:
1 |
recyclerView.setHasFixedSize(true); |
3. Use the default RecyclerView drawing cache methods and tweak them according to your case. You don’t need a third party library to do so:
1 2 3 |
recyclerView.setItemViewCacheSize(20); recyclerView.setDrawingCacheEnabled(true); recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH); |
4. If you use many images, make sure their size and compression are optimal. Scaling images may also affect performance. There are two sides to the problem – the source image used and the decoded Bitmap.
1 2 3 4 |
InputStream is = (InputStream) url.getContent(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.RGB_565; Bitmap image = BitmapFactory.decodeStream(is, null, options); |
5. Make sure onBindViewHolder() is as cheap as possible. You can set OnClickListener once in onCreateViewHolder() and call through an interface a listener outside of the Adapter, passing the clicked item. This way you don’t create extra objects all the time. Also check flags and states, before making any changes to the view here.
1 2 3 4 5 6 7 |
viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Item item = getItem(getAdapterPosition()); outsideClickListener.onItemClicked(item); }} ); |
6. When data gets changed, try to update only the affected items. For example instead of invalidating the whole data set with notifyDataSetChanged(), when adding/loading more items, just use:
1 2 3 4 |
adapter.notifyItemRangeInserted(rangeStart, rangeEnd); adapter.notifyItemRemoved(position); adapter.notifyItemChanged(position); adapter.notifyItemInserted(position); |
Rely on notifyDataSetChanged() as a last resort.
But if you need to use it, maintain your items with unique ids:
1 |
adapter.setHasStableIds(true); |
I hope this blog will help you to optimize the recycleview in your application.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.