1. 程式人生 > >Android RecyclerView多佈局的實現

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

    }