android - 了解 RecyclerView setHasFixedSize

标签 android android-5.0-lollipop android-recyclerview

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

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

最佳答案

一个非常简化版的 RecyclerView 有:

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

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

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


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

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 if adapter changes cannot affect the size of the RecyclerView.

关于android - 了解 RecyclerView setHasFixedSize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28709220/

相关文章:

android - 在 Android 5.0 上的 Activity 之间转换时如何排除 ActionBar

android - 在 RecyclerView 中使用 onClick() 启动新 Activity

安卓+ eclipse : Can't push files to SD Card

android - 提升在 Android L 中做什么?

android - Retrofit + SimpleXMLConverter 适用于 Lollipop,不适用于 Kitkat

java - Intent 的 RecyclerView 中未检测到 OnClick

android - 如何在列表项中添加水平 RecyclerView

java - 使用 setText 和 onClickListener 将数据从 EditText 传输到另一个 Activity 的 TextView?

java - 改造中设置宽松错误 :1. 8.0

android - 如何在 Android 操作系统上托管 Web 应用程序