最近需要用RecyclerView嵌套来实现一个功能,具体说就是在文章列表的item中显示若干图片。
实现起来并不难,只需要在外层item的适配器中,在onBind方法中绑定内层item的适配器。
由于这里使用的是RecyclerView,所以需要设置它的LayoutManager,在设置的时候,发现普通的GridLayoutManager无法显示视图,后来明白是内层Layout无法获取视图的宽高属性,需要重写onMeasure方法,计算每一个item的宽高属性。
具体代码如下:
public class MyGridLayoutManager extends GridLayoutManager {
private int spanCount;
private int parentWidth;
private int width = 0;
private int height = 0;
public MyGridLayoutManager(Context context, int spanCount, int parentWidth) {
super(context, spanCount);
this.parentWidth = parentWidth;
this.spanCount = spanCount;
}
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int itemCount = getItemCount();
for(int i = 0; i < itemCount; i++){
width = parentWidth/spanCount;
if(itemCount%spanCount == 0){
height = (itemCount/spanCount)*width;
}else {
height = (itemCount/spanCount+1)*width;
}
}
width = widthSize;
setMeasuredDimension(width, height);
}
}
等有时间会再详细说明一下它的实现,现在已经很晚了。