使用下面的代码,默认一行3个child
recyclerView.setLayoutManager(new GridLayoutManager(activity, 3) {
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
super.onMeasure(recycler, state, widthSpec, heightSpec);
int measuredWidth = recyclerView.getMeasuredWidth();
int measuredHeight = recyclerView.getMeasuredHeight();
int myMeasureHeight = 0;
int count = state.getItemCount();
for (int i = 0; i < count; i++) {
View view = recycler.getViewForPosition(i);
if (view != null) {
if (myMeasureHeight < measuredHeight && i % 3 == 0) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
myMeasureHeight += view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
}
recycler.recycleView(view);
}
}
// Log.i("Height", "" + Math.min(measuredHeight, myMeasureHeight));
setMeasuredDimension(measuredWidth, Math.min(measuredHeight, myMeasureHeight));
}
|