RecyclerView setHasFixedSize(true); 的作用

下文翻译:RecyclerView的尺寸在每次改变时,比如你加任何些东西。setHasFixedSize 的作用就是确保尺寸是通过用户输入从而确保RecyclerView的尺寸是一个常数。RecyclerView 的Item宽或者高不会变。每一个Item添加或者删除都不会变。如果你没有设置setHasFixedSized没有设置的代价将会是非常昂贵的。因为RecyclerView会需要而外计算每个item的size,

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

原文

RecyclerView size changes every time you add something no matter what. What setHasFixedSize does is that it makes sure (by user input) that this change of size of RecyclerView is constant. The height (or width) of the item won't change. Every item added or removed will be the same. If you dont set this it will check if the size of the item has changed and thats expensive. Just clarifying because this answer is confusing. – ArnoldB May 25 at 18:42

very simplified version of RecyclerView has:

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

requestLayout()是很昂贵的,因为他会要求重新布局,重新绘制(详细请看Android优化),所以如当不是瀑布流时,设置这个可以避免重复的增删造成而外的浪费资源

RecyclerView size changes every time you add something no matter what. What setHasFixedSize does is that it makes sure (by user input) that this change of size of RecyclerView is constant. The height (or width) of the item won't change. Every item added or removed will be the same. If you dont set this it will check if the size of the item has changed and thats expensive. Just clarifying because this answer is confusing. – ArnoldB May 25 at 18:42

翻译:

Recyclerview的大小会随着你每次添加的东西而变化。setHasFixedSize所做的是(通过用户输入)确保recycle view的大小变化是恒定的。视图的高度(或宽度)不会更改。每项添加或删除的内容都是相同的。如果你不设置这个,它会检查物品的大小是否改变了,这是昂贵的。仅仅在此说明一下,这个令人费解的答案。- 5月25日18时42分

发布了59 篇原创文章 · 获赞 13 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Hunter2916/article/details/100115600