Wandy Liem Wandy Liem - 17 days ago 11
Android Question

Recyclerview with different type

Hi guys I'm trying to populate

RecyclverView
with different collections.. For example I got 2 list lets say customer list and supplier list.

What I want to achieve is :


  • customer header







  • Customer 1

  • Customer 2







  • supplier header







  • Supplier 1

  • Supplier 2



Is that possible? Thanks.

Sorry for my English

Answer

It's possible to do this with RecyclerView, you should override getItemViewType() method.

Like this:

private class CustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int TYPE_1 = 1;
    private static final int TYPE_2 = 2;
    private static final int TYPE_3 = 3;
    // more types...

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case TYPE_1:
                break;
            case TYPE_2:
                break;
            case TYPE_3:
                break;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case TYPE_1:
                break;
            case TYPE_2:
                break;
            case TYPE_3:
                break;
        }
    }

    @Override
    public int getItemViewType(int position) {
        if(position == 1) {
            return TYPE_1;
        } else if(position == 2) {
            return TYPE_2;
        } else 
            return TYPE_3
    }

    @Override
    public int getItemCount() {
        return 10;
    }
}
Comments