Reputation: 107
I try loading image (696x373) from drawable following 3 different ways:
setImageDrawable()
In this case, loading image is pretty fast, smooth scrolling in recyclerview.
override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) {
val category = categories[position]
holder.bindViewHolder(context,category, position, SELECTED_ITEM, onClickedCategoryItem)
}
class CategoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindViewHolder(
context: Context,
category: Category,
position: Int,
selectedItem: Int,
onClickedCategoryItem: (Int) -> Unit) {
with(itemView) {
image.setImageDrawable(ContextCompat.getDrawable(context, category.imageId))
}
}
}
setImageResource()
similar to abovesetImageBitmap()
with decode sampled bitmap,It is so heavy compare to 2 above cases.
image.setImageBitmap(BitmapUtils.decodeSampledBitmapFromResource(context.resources, category.imageId, image.width, image.height))
I don't understand why it is, can everyone explain for me?
Upvotes: 0
Views: 372
Reputation: 1741
See the docs for handling bitmaps:
Loading bitmaps on the UI thread can degrade your app's performance, causing slow responsiveness or even ANR messages. It is therefore important to manage threading appropriately when working with bitmaps.
So you should either reinvent the wheel and handle threading by yourself or use a 3rd party library like Glide.
There are several libraries that follow best practices for loading images. You can use these libraries in your app to load images in the most optimized manner. We recommend the Glide library, which loads and displays images as quickly and smoothly as possible. Other popular image loading libraries include Picasso from Square and Fresco from Facebook. These libraries simplify most of the complex tasks associated with bitmaps and other types of images on Android
Upvotes: 1