Sobes.tech
Junior — Middle

What functions need to be overridden in a RecyclerView adapter to display a list with different item types?

sobes.tech AI

Answer from AI

To display a list with different item types in a RecyclerView adapter, you need to override the following functions:

  1. getItemViewType(int position) — returns an integer identifier of the item type at the given position. This allows the adapter to understand which layout to use for a specific item.

  2. onCreateViewHolder(ViewGroup parent, int viewType) — creates a ViewHolder of the corresponding type based on viewType, obtained from getItemViewType.

  3. onBindViewHolder(RecyclerView.ViewHolder holder, int position) — binds data to the ViewHolder, considering the item type.

Example:

@Override
public int getItemViewType(int position) {
    if (isTypeA(position)) {
        return TYPE_A;
    } else {
        return TYPE_B;
    }
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if (viewType == TYPE_A) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_type_a, parent, false);
        return new TypeAViewHolder(view);
    } else {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_type_b, parent, false);
        return new TypeBViewHolder(view);
    }
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (holder instanceof TypeAViewHolder) {
        ((TypeAViewHolder) holder).bind(data.get(position));
    } else if (holder instanceof TypeBViewHolder) {
        ((TypeBViewHolder) holder).bind(data.get(position));
    }
}

Thus, these methods provide support for multiple item types within a single list.