重写LayoutManger的onMeasure方法,这种方式可以获取到各个item的不同高度,从而可以设置变动的高度。


在使用这种方式时,有一点需要注意的是,不要将RecyclerView的android:layout_height属性设置为wrap_content,不然是不会成功的。

小于四高度自适应,大于四高度就固定


recyclerView.setLayoutManager(new LinearLayoutManager(this) { @Override public
voidonMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int
widthSpec, int heightSpec) { int count = state.getItemCount(); if (count > 0) {
if(count>4){ count =4; } int realHeight = 0; int realWidth = 0; for(int i = 0;
i < count; i++){ View view = recycler.getViewForPosition(0); if (view != null)
{ measureChild(view, widthSpec, heightSpec); int measuredWidth =
View.MeasureSpec.getSize(widthSpec); int measuredHeight =
view.getMeasuredHeight(); realWidth = realWidth > measuredWidth ? realWidth :
measuredWidth; realHeight += measuredHeight; } setMeasuredDimension(realWidth,
realHeight); } } else { super.onMeasure(recycler, state, widthSpec, heightSpec);
} } });

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:637538335
关注微信