美文网首页
BaseMultiItemQuickAdapter实现多布局

BaseMultiItemQuickAdapter实现多布局

作者: jiluyixia | 来源:发表于2020-07-10 10:28 被阅读0次

有种需求,在点击按钮的时候,改变RecyclerView的列数以及布局。


1111.png 22222.png

如果用的RecyclerView.Adapter适配器,用getItemViewType就可以做,但是项目中,用的是BaseQuickAdapter。
查找资料,发现可以改为BaseMultiItemQuickAdapter实现多布局。
class GoodsItemAdapter extends BaseMultiItemQuickAdapter<GoodsSearchVO.GoodsBean, BaseViewHolderExt> {
在GoodsItemAdapter 里

public GoodsItemAdapter(List<GoodsSearchVO.GoodsBean> data) {
            super(data);
            addItemType(1, R.layout.fragment_goods_search_list_item);
            addItemType(2, R.layout.fragment_goods_search_list_item_single);
}

然后在convert里,配置不同的布局。

@Override
        protected void convert(@NonNull BaseViewHolderExt helper, GoodsSearchVO.GoodsBean item) {
        switch (helper.getItemViewType()) {
            case 1:
                helper.setText(R.id.tv_item_smart_refresh, item.getName());
                GlideApp.with(mContext).load(item.getBgPicture()).into((ImageView) helper.getView(R.id.iv_item_smart_refresh));
                break;
            case 2:
                helper.setText(R.id.tv_item_smart_refresh_2, item.getName());
                break;
        }
    }
}

这样做的关键是,在GoodsBean 里面,有一个itemType参数,通过itemType值的不同,设置不同的布局。
所以在点击按钮的时候

case R.id.tv_preview_type:
                setLayoutManager();

更改sapncount以及itemType,再setNewData更新数据即可。

public void setLayoutManager(){
        itemType = itemType == ITEM_DOUBLE ? ITEM_SINGLE:ITEM_DOUBLE;

        switch (itemType){
            case ITEM_DOUBLE :
                mGoodsListRV.setLayoutManager(new GridLayoutManager(getContext(), 2));
            break;
            case ITEM_SINGLE :
                mGoodsListRV.setLayoutManager(new GridLayoutManager(getContext(), 1));
            break;
        }
        for(GoodsSearchVO.GoodsBean item :mGoodsItemAdapter.getData()){
            item.setItemType(itemType);//设置itemType,在GoodsItemAdapter里选择布局
        }
        mGoodsItemAdapter.setNewData(mGoodsItemAdapter.getData());
    }

注意,item.setItemType(itemType);的前提是,GoodsSearchVO.GoodsBean要implements MultiItemEntity,并且重写

@Override
        public int getItemType() {
            return itemType;
        }

参考资料:万能适配器BaseQuickAdapter多布局的用法

相关文章

网友评论

      本文标题:BaseMultiItemQuickAdapter实现多布局

      本文链接:https://www.haomeiwen.com/subject/utypcktx.html