了解 RecyclerView setHasFixedSize [英] Understanding RecyclerView setHasFixedSize

查看:27
本文介绍了了解 RecyclerView setHasFixedSize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解 setHasFixedSize() 时遇到了一些问题.我知道当 RecyclerView 的大小没有改变时,它用于优化,来自文档.

I'm having some trouble understanding setHasFixedSize(). I know that it is used for optimization when the size of RecyclerView doesn't change, from the docs.

那是什么意思?在最常见的情况下,ListView 几乎总是有一个固定的大小.在什么情况下它不是固定大小?这是否意味着它在屏幕上所占的实际空间会随着内容而增长?

What does that mean though? In most common cases a ListView almost always has a fixed size. In what cases would it not be a fixed size? Does it mean that the actual real estate that it occupies on screen grows with the content?

推荐答案

RecyclerView 的一个非常简化版具有:

A very simplified version of RecyclerView has:

void onItemsInsertedOrRemoved() {
   if (hasFixedSize) layoutChildren();
   else requestLayout();
}

此链接 描述了为什么调用 requestLayout 可能很贵.基本上,每当项目被插入、移动或移除时, RecyclerView 的大小(宽度和高度)可能会发生变化,而视图层次结构中任何其他视图的大小也可能会发生变化.如果经常添加或删除项目,这尤其麻烦.

This link describes why calling requestLayout might be expensive. Basically whenever items are inserted, moved or removed the size (width and height) of RecyclerView might change and in turn the size of any other view in view hierarchy might change. This is particularly troublesome if items are added or removed frequently.

当更改适配器的内容不会更改其高度或宽度时,通过将 setHasFixedSize 设置为 true 来避免不必要的布局传递.

Avoid unnecessary layout passes by setting setHasFixedSize to true when changing the contents of the adapter does not change it's height or the width.

更新:JavaDoc 已更新以更好地描述该方法的实际作用.

Update: The JavaDoc has been updated to better describe what the method actually does.

RecyclerView 可以执行多项优化,如果它可以知道提前确保 RecyclerView 的大小不受适配器影响内容.RecyclerView 仍然可以根据其他改变其大小因素(例如其父级的大小),但此大小计算不能取决于其子项的大小或其适配器的内容(除了适配器中的项目数).

如果你使用 RecyclerView属于这一类,将其设置为 {@code true}.它将允许RecyclerView 避免在其适配器时使整个布局无效内容改变.

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 {@code true}. It will allow RecyclerView to avoid invalidating the whole layout when its adapter contents change.

@param hasFixedSize 如果适配器更改不会影响大小,则为 true回收器视图.

@param hasFixedSize true if adapter changes cannot affect the size of the RecyclerView.

这篇关于了解 RecyclerView setHasFixedSize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆