I want to create a complex recycler view with different rows.
How it is possible?
Like this picture: Three types of list
You can display severel types of listview row layout in your RecyclerView - you dont need multiple adapters
You need to override the getItemCount and the getItemViewType methods of the recycler view and tell it how much types you want to display in the list look at this: RecyclerView item count
Here is an example:
the adapter:
public class NotificationsAdapter extends RecyclerView.Adapter<MultipleRowViewHolder> {
private LayoutInflater inflater = null;
// notification list
private List<Notification> notificationList;
public NotificationsAdapter(Context context, List<Notification> multipleRowModelList){
this.notificationList = multipleRowModelList;
inflater = LayoutInflater.from(context);
}
@Override
public MultipleRowViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
if (viewType == NotificationType.Lick.getValue())
view = inflater.inflate(R.layout.lick_row_item, parent, false);
else if (viewType == NotificationType.Comment.getValue())
view = inflater.inflate(R.layout.comment_list_row, parent, false);
else if (viewType == NotificationType.ViewMyProfile.getValue())
view = inflater.inflate(R.layout.view_my_profile_list_row, parent, false);
else // if notification is not of the first three types get the view_my_profile_list_row layout
view = inflater.inflate(R.layout.view_my_profile_list_row, parent, false);
return new MultipleRowViewHolder(view, viewType);
}
@Override
public void onBindViewHolder(MultipleRowViewHolder holder, int position) {
try {
// display enum type as title
holder.titleTV.setText(NotificationType.toNotificationType(Integer.valueOf(notificationList.get(position).getType())).name());
// display pretty date
holder.actionTimeTV.setText(TimeUtils.getPrettyTimeDifference(notificationList.get(position).getActionTime()));
holder.sourceUserNameTV.setText(notificationList.get(position).getSourceUserName());
}catch (Exception e)
{
Log.e(NotificationReader.TAG,e.getMessage());
}
}
@Override
public int getItemCount() {
return notificationList.size();
}
@Override
public int getItemViewType(int position) {
Notification multipleRowModel = notificationList.get(position);
if (multipleRowModel != null)
return Integer.valueOf(multipleRowModel.getType());
return super.getItemViewType(position);
}
The data model:
public class MultipleRowViewHolder extends RecyclerView.ViewHolder {
public TextView titleTV;
public TextView sourceUserNameTV;
public TextView actionTimeTV;
private int type;
public MultipleRowViewHolder(View itemView, int type) {
super(itemView);
titleTV = (TextView)itemView.findViewById(R.id.titleTV);
sourceUserNameTV = (TextView)itemView.findViewById(R.id.sourceUserNameTV);
actionTimeTV = (TextView)itemView.findViewById(R.id.actionTimeTV);
this.type = type;
}
}