Android中當item數量超過必定大小時,將RecyclerView高度固定
方法1
直接經過LayoutParams來設定相應高度
ViewGroup.LayoutParams lp = rv.getLayoutParams(); if (list.size() > 4) { lp.height = DensityUtil.dip2px(mContext,32 * 4); } else { lp.height = DensityUtil.dip2px(mContext,34 * list.size()); } rv.setLayoutParams(lp);
該方法只適用於item高度固定,在本例中使用34dp來設置相應的item高度,故而能夠經過乘上相應的item數來計算RecyclerView的高度。android
方法2
重寫LayoutManger的onMeasure方法,這種方式能夠獲取到各個item的不一樣高度,從而能夠設置變更的高度。
在使用這種方式時,有一點須要注意的是,不要將RecyclerView的android:layout_height屬性設置爲wrap_content,否則是不會成功的。ide
rv.setLayoutManager(new LinearLayoutManager(mContext) { @Override public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) { int count = state.getItemCount(); if (count > 0) { 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 : measureWidth; realHeight += measureHeight; } setMeasuredDimension(realWidth, realHeight); } } else { super.onMeasure(recycler, state, widthSpec, heightSpec); } } });
方法中的recycler是一個item的循環使用器,起到對item管理的做用。spa