有时候,我们会遇到这种需求:一个线性的列表布局,当item量很少的时候,就是wrap_content直接展示完所有item,但是当item数量超过某个数时就要固定高度,让其变成可滑动展示更多的item。所以我们第一个想法就是用RecyclerView,应该没人会用ListView或自己写个自定义ViewGroup吧。
但是当我们使用RecyclerView+maxHeight的时候,会发现其实maxHeight是不起作用的。
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxHeight="100dp" />
复制代码
image
那么为什么会造成这种原因呢?其实在我之前写的一篇博客也提到过:RecyclerView将onMeasure的转交给了LayoutManager,并且LayoutManager里面有个isAutoMeasureEnabled()方法用来配置LayoutManager是否开启自测量。我们常用的LinearLayoutManager或GridLayoutManager都是默认返回true的。
实现思路
所以实现思路就很简单了:设定一个maxLine参数,当RecyclerView的itemCount小于这个值is