将视图插入Recycler视图

时间:2016-03-20 19:52:00

标签: android android-recyclerview android-sdk-tools

我有像ListView一样的RecyclerView的一些数据。我必须在该列表中放置3个不同的视图。它像行“用户名”或“联系人”,我该怎么做?

1 个答案:

答案 0 :(得分:1)

创建一个视图持有者:

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

  public abstract  void setDataOnView(int position);
}

现在创建视图持有者并使它们扩展ViewHolder。像这样:

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);
    }
   }
 }

最后,RecyclerView.Adapter类可以是:

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);
  }

希望可以帮助你:)