1. 程式人生 > >RecycleView 顯示不同佈局

RecycleView 顯示不同佈局

1. 在RecycleAdapter中,設定不同佈局的position:(使用如下命名可更清晰)

    private static final int TITLE = 0; //標題 -- 等待買家付款
    private static final int ADDRESS = 1; //地址
    private static final int GOODS = 2; //商品列表

    private Context mContext;
    private LayoutInflater mLayoutInflater;

2. 重寫getItemViewType方法 ,根據不同position返回不同佈局

@Override
    public int getItemViewType(int position) {
        switch (position){
            case TITLE:
                return TITLE;
            case ADDRESS:
                return ADDRESS;
            case GOODS:
                return GOODS;
        }
        return TITLE;
    }

3. 根據返回的viewType createViewHolder

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == TITLE){
            return new TitleViewHolder(mLayoutInflater.inflate(R.layout.wait_item_title,null)); //佈局
        }else if (viewType == ADDRESS){
            return new AddressViewHolder(mLayoutInflater.inflate(R.layout.order_address, null));
        }else if (viewType == GOODS){
            
        }
        return null;
    }

4. 根據不同佈局繫結資料

@Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position)==ADDRESS){
            AddressViewHolder addressViewHolder = (AddressViewHolder) holder;
            addressViewHolder.setData(addressBean, mContext);
        }else if (getItemViewType(position)==GOODS){
            GoodsViewHolder goodsViewHolder = (GoodsViewHolder) holder;
            goodsViewHolder.setData();
        }
    }

5. 修改一下要返回的佈局數

@Override
    public int getItemCount() {
        return 3;
    }

ViewHolder寫法示例:

/**
     * 商品資訊 ViewHolder
     */
    private class GoodsViewHolder extends RecyclerView.ViewHolder {
        private OrderConfirmGridView waitItemGrv;
        private TextView waitItemGoodsprice;
        private TextView waitItemDesprice;
        private TextView waitItemTotal;
        public GoodsViewHolder(View view) {
            super(view);
            waitItemGrv = (OrderConfirmGridView)view.findViewById( R.id.wait_item_grv );
            waitItemGoodsprice = (TextView)view.findViewById( R.id.wait_item_goodsprice );
            waitItemDesprice = (TextView)view.findViewById( R.id.wait_item_desprice );
            waitItemTotal = (TextView)view.findViewById( R.id.wait_item_total );
        }

        public void setData() {
            grvAdapter = new CheckOrderGrvAdapter(mContext, orderInfoVo.getRows());
            waitItemGrv.setAdapter(grvAdapter);
        }
    }