具有多种动态类型的Recyclerview查看

时间:2015-10-09 06:35:24

标签: android android-recyclerview recycler-adapter

当项目的类型是动态的时,我对Recyclerview有疑问。这意味着我不知道有多少种类型的Recyclerview项目。所以我不知道#&# 39;知道如何在onCreateViewHolder()中编写MyAdapter extends RecyclerView.Adpter<RecylerView.ViewHolder>

但事实上,这些项目遵循一些法律。例如:

ITEM1:

Text(title)
Pic(Vertical) Pic(Vertical) Pic(Vertical)
Pic(Vertical) Pic(Vertical) Pic(Vertical)

ITEM2:

Text(title)
Pic(Horizontal) Pic(Horizontal)
Pic(Horizontal) Pic(Horizontal)

如果图片为垂直,则列为三。如果图片为水平,则列为2。图片的数量可能为一,二,三,四,五,六等,所以类型I无法确认。 我很抱歉,因为我无法展示图片。我问了一个问题RecyclerView with GridView

但它并没有解决我的问题。我看到了How to create RecyclerView with multiple view type?

但类型没有变化。 PS:我知道图片是垂直的或水平的数据。

1 个答案:

答案 0 :(得分:2)

你不能创建两个自定义ViewHolder并检查哪一个传入onCreateviewHolder,如本答案所示? How to create RecyclerView with multiple view type?

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

class ViewHolder0 extends RecyclerView.ViewHolder {
   //viewHolder for horitzontal pics
    ...
}

class ViewHolder2 extends RecyclerView.ViewHolder {
    ...
    //viewHolder for vertical pics
}

@Override
public int getItemViewType(int position) {
    // Just as an example, return 0 or 2 depending on position
    // Note that unlike in ListView adapters, types don't have to be contiguous
    return position % 2 * 2;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
     switch (viewType) {
         case 0: return new ViewHolder0(...);
         case 2: return new ViewHolder2(...);
         ...
     }
}

}

docs中,您可以扩展RecyclerView.ViewHolder

// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
    // each data item is just a string in this case
    public TextView mTextView;
    public ViewHolder(TextView v) {
        super(v);
        mTextView = v;
    }
}