Android RecyclerView多布局的实现

主要操作实在Adapter中的。区别于正常RecyclerView的Adapter。首先是定义几个全局的变量来标识有几种布局。
public static final int ONE_ITEM = 1;
public static final int TWO_ITEM = 2;
public static final int THREE_ITEM = 3;

然后除了正常的方法之外,还要重写getItemViewType的方法,其中根据不同的判断条件来返回不同的结果。
@Override
    public int getItemViewType(int position) {
        if (list.get(position).getFromtype().equals("2")) {
            return TWO_ITEM;
        } else if (list.get(position).getFromtype().equals("1")) {
            return ONE_ITEM;
        } else {
            return THREE_ITEM;
        }
    }
在onCreateViewHolder中也要进行区分,以加载不同的item布局(有几种布局就创建几个ViewHolder)。
@Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // 给ViewHolder设置布局文件
        RecyclerView.ViewHolder holder = null;
        if (ONE_ITEM == viewType) {
            View v = inflater.inflate(R.layout.layout_dbxianshi, parent, false);
            holder = new ViewHolder1(v);
        } else if (TWO_ITEM == viewType) {
            View v = inflater.inflate(R.layout.layout_dbshenhe, parent, false);
            holder = new ViewHolder2(v);
        } else {
            View v = inflater.inflate(R.layout.layout_dbfj, parent, false);
            holder = new ViewHolder3(v);
        }
        return holder;
    }
最后在onBindViewHolder中对每种布局进行不同的操作。
@Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        DBXQModel model = list.get(position);
        if (holder instanceof ViewHolder1) {
            ((ViewHolder1) holder).label.setText(model.getLabel());
            ((ViewHolder1) holder).content.setText(model.getContent());
        } else if (holder instanceof ViewHolder2) {
            ((ViewHolder2) holder).label.setText(model.getLabel());
            ((ViewHolder2) holder).content.setText(model.getContent());
            ((ViewHolder2) holder).name.setText(model.getName());
            ((ViewHolder2) holder).time.setText(model.getTime());
        } else {
            ((ViewHolder3) holder).name_fj.setText(model.getLabel());
        }
        holder.itemView.setTag(position);

    }




你可能感兴趣的:(Android,Android开发)