1. 程式人生 > >RecyclerView載入不同型別的佈局

RecyclerView載入不同型別的佈局

       RecyclerView有什麼優點以及和ListView有什麼區別就不多說了,今天來實現RecyclerView的不同item佈局效果,直接上圖:


       實現的思路是為資料新增一個type,根據type的值來判定getItemViewType返回的型別。getItemViewType(int position)返回的值就是onCreateViewHolder(ViewGroup parent, int viewType)的引數viewType,所以根據不同的值載入不同的佈局。程式碼如下:

public class MyAdapter extends RecyclerView.Adapter
<RecyclerView.ViewHolder>{ public static enum ITEM_TYPE{ ITEM_TYPE_LEFT, ITEM_TYPE_RIGHT; } private LayoutInflater layoutInflater; private Context context; private List<Content> contents; public MyAdapter(Context c, List<Content> strs){ layoutInflater = LayoutInflater.from(c); context
= c; contents = strs; } @Override public int getItemCount() { return contents != null ? contents.size() : 0; } @Override public int getItemViewType(int position) { return contents.get(position).getType() == 0 ? ITEM_TYPE.ITEM_TYPE_LEFT.ordinal() : ITEM_TYPE.ITEM_TYPE_RIGHT.ordinal() ; } @Override public
RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if(viewType == ITEM_TYPE.ITEM_TYPE_LEFT.ordinal()){ return new LeftViewHolder(layoutInflater.inflate(R.layout.item_text_left,parent,false)); }else{ return new RightViewHolder(layoutInflater.inflate(R.layout.item_text_right,parent,false)); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if(holder instanceof LeftViewHolder){ ((LeftViewHolder) holder).tv_left.setText(contents.get(position).getMessage()); }else if(holder instanceof RightViewHolder){ ((RightViewHolder) holder).tv_right.setText(contents.get(position).getMessage()); } } public static class LeftViewHolder extends RecyclerView.ViewHolder{ public TextView tv_left; public LeftViewHolder(View v){ super(v); tv_left = (TextView)v.findViewById(R.id.tv_left); } } public static class RightViewHolder extends RecyclerView.ViewHolder{ public TextView tv_right; public RightViewHolder(View v){ super(v); tv_right = (TextView)v.findViewById(R.id.tv_right); } } }