RecyclerView的嵌套使用

最近需要用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);
    }
}
等有时间会再详细说明一下它的实现,现在已经很晚了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值