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:
-
getItemViewType(int position)— returns an integer identifier of the item type at the givenposition. This allows the adapter to understand which layout to use for a specific item. -
onCreateViewHolder(ViewGroup parent, int viewType)— creates a ViewHolder of the corresponding type based onviewType, obtained fromgetItemViewType. -
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.