-1

I have RecyclerView like ListView of some data.I must to put 3 different view to that list.Its like row "Username" or "Contacts",how can I do that?

Rost
  • 53
  • 8
  • 5
    Please see this link... http://stackoverflow.com/questions/26245139/how-to-create-recyclerview-with-multiple-view-type – JpCrow Mar 20 '16 at 21:26

1 Answers1

1

Create a view holder:

public abstract class ViewHolder extends RecyclerView.ViewHolder {
  public ViewHolder(View itemView) {
    super(itemView);
  }

  public abstract  void setDataOnView(int position);
}

Now create your view holders and make them extend the ViewHolder. Like this:

public class ContentViewHolder extends ViewHolder{
public final View view;
public final TextView tv_div;

public ContentViewHolder(View itemView) {
    super(itemView);
    view = itemView;
    tv_div = (TextView) view.findViewById(R.id.tv_div);
}

@Override
public void setDataOnView(int position) {
    try {
        String title= sections.get(position);
        if(title!= null)
            this.tv_div.setText(title);
    }catch (Exception e){
        new CustomError("Error!"+e.getMessage(), null, false, null, e);
    }
   }
 }

finally the RecyclerView.Adapter class could be:

public class MyRecyclerViewAdapter extends 
RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

@Override
 public int getItemViewType(int position) {
   // depends on your problem
      switch (position) {
        case : return VIEW_TYPE1;
        case : return VIEW_TYPE2;
        ...
     }
   }

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
  View view;

   if(viewType == VIEW_TYPE1){
     view = LayoutInflater.from(parent.getContext()).inflate      
      (R.layout.layout1, parent, false);
     return new ContentViewHolder(view);

   } else if( viewType == VIEW_TYPE2){
     view = LayoutInflater.from(parent.getContext()).inflate
     (R.layout.layout2, parent, false);
     return new OtherViewHolder(view);
   }

    // Cont. other view holders ...
     return null;
  }

   @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
    holder.setDataOnView(position);
  }

Hope can help you :)