Janos Janos - 1 month ago 25
Android Question

How to change the recyclerview first row layout?

I want to add different layout for the first row, how can i set it up?

Adapter class:
This is the normal, all row equals:

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
inflater=LayoutInflater.from(parent.getContext());
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_trends, parent, false));
}


And what to change in the OnBindViewHolder method?

Answer

First you need to override getItemViewType. Return itemType according to your requirements.

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

then in onCreateViewHolder inflate your different layout according to your viewType.

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if (viewType == 1) {
        // inflate your first item layout & return that viewHolder
    } else {
        // inflate your second item layout & return that viewHolder
    }
}