前言
下面提供了2種方式,看情況選擇使用。
代碼部分
方式一
可靠且簡單暴力的方式,需要讓RecyclerView先setAdapter();
mRecyclerview.post(new Runnable() { //將修改高度的代碼放到RecyclerView最后面執行,讓RecyclerView先測量完畢 @Override public void run() { if (mRecyclerview.getAdapter() == null || mRecyclerview.getAdapter().getItemCount() <= 4){ //小於4個不固定高度 return; } View view = mRecyclerview.getChildAt(0); if (view == null){ return; } int height = view.getHeight() * 4; ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) mRecyclerview.getLayoutParams(); layoutParams.height = height; mRecyclerview.setLayoutParams(layoutParams); } });
方式二
可能會被父類的布局測量影響
使用時,請注意2點情況:
- 不要將RecyclerView的android:layout_height屬性設置為wrap_content,不然是不會成功的.
- item的根布局也需要固定高度,不要使用wrap_content,否則下面測算高度時會出現不准確的情況.
/** * 自適應列表View在到指定數量item后固定高度, * * @param targetNum */ private void adaptiveRecyclerViewHeight(int targetNum) { mFamilyListRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()) { @Override public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) { int count = state.getItemCount(); if (count > 0) { if (count > targetNum) { count = targetNum; } 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 = realHeight + measuredHeight; } } setMeasuredDimension(realWidth, realHeight); } else { super.onMeasure(recycler, state, widthSpec, heightSpec); } } }); }
End