Fresco 在RecyclerView中的优化

参考地址:

https://code.luasoftware.com/tutorials/android/android-fresco-optimize-performance-for-recyclerview/

RecylerView

Consider RecyclerView.hasFixedSize

RecyclerView can perform several optimizations if it can know in advance that RecyclerView’s size is not affected by the adapter contents. RecyclerView can still change its size based on other factors (e.g. its parent’s size) but this size calculation cannot depend on the size of its children or contents of its adapter (except the number of items in the adapter).

If your use of RecyclerView falls into this category, set this to true. It will allow RecyclerView to avoid invalidating the whole layout when its adapter contents change.

class LocalAdapter() : RecyclerView.Adapter<LocalAdapter.ViewHolder>() {
 private var items = ...
​
 init {
 setHasStableIds(true)
 }
​
 override fun getItemId(position: Int): Long {
 // return items[position].id
 return items[position].hashCode().toLong()
 }
}

Fresco

Enable Fresco downsampling

val config = ImagePipelineConfig.newBuilder(context)
 .setDownsampleEnabled(true)
 .build()
Fresco.initialize(context, config)

Use ResizeOptions

// I am using GridLayout with 3 columns
val estimatedImageSize = Resources.getSystem().displayMetrics.widthPixels / layoutManager.spanCount
val adapter = LocalAdapter(viewModel, estimatedImageSize)</pre>
class LocalAdapter(val estimatedImageSize: Int) : RecyclerView.Adapter<LocalAdapter.ViewHolder>() {
​
 private var resizeOptions: ResizeOptions? = null
 private var items = ...
​
 override fun onBindViewHolder(holder: ViewHolder, position: Int) {
 val item = items[position]
​
 // try to get exact size at runtime when DraweeView is rendered
 val localResizeOptions = if (resizeOptions == null) {
 holder.draweeView.doOnLayout {
 resizeOptions = ResizeOptions(holder.draweeView.width, holder.draweeView.height)
 }
 ResizeOptions(estimatedImageSize, estimatedImageSize)
 }
 else resizeOptions
​
 val request =
 ImageRequestBuilder.newBuilderWithSource(item.uri)
 .setResizeOptions(localResizeOptions)
 .build()
 holder.draweeView.setImageRequest(request)
 }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容