例子:
@Override
public int getItemViewType(int position) {
// you should return the view type, based on your own dynamic logic
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
// handle each view type accordingly
}
}
public class Data{
int field1;
float filed2;
int rowType // 1,2,2,...N this will fill by you whenever you will
//creating arraylist for your recyclerview
}
public class Custome Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ArrayList<Data> mItems;
class ViewHolderRowType1 extends RecyclerView.ViewHolder {
...
}
class ViewHolderRowType2 extends RecyclerView.ViewHolder {
...
}
....
class ViewHolderRowTypeN extends RecyclerView.ViewHolder {
...
}
@Override
public int getItemViewType(int position) {
return mItems.get(position).rowType;
//or
//return positon%2; // This will based on your condition
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0: return new ViewHolderRowType0(...);
case 1: return new ViewHolderRowType1(...);
...
case N: return new ViewHolderRowTypeN(...);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder vh, int position) {
//Just check which view type is going to bind and then fill the data accordingly in your rows
if(vh instanceof ViewHolderRowType1){
// Fill the data for first view type
} else if (vh instanceof ViewHolderRowType2) {
// Fill the data for second view type
} else if (vh instanceof ViewHolderRowTypeN){
// Fill the data for Nth view type
}
}
RecyclerView
顶部,然后通过RecyclerView的滚动事件进行处理。有两种实现 RecyclerView
的方式:
在自定义的 POJO / GetterSetter 类中,添加一个用于 headerStatus
(布尔值或整数) 的字段,以标识是否显示标题。
现在在适配器中覆盖 public int getItemViewType(int position)
方法。
static final int TYPE_ITEM = 0;
static final int TYPE_SEPARATOR = 1;
@Override
public int getItemViewType(int position) {
if (mData.get(position).getHeaderStatus() == 0)
return TYPE_ITEM;
else
return TYPE_SEPARATOR;
}
现在,在getView()
中填充布局时,您可以通过以下方式检查行类型:
int rowType = getItemViewType(position);
对于情况1,您需要显示标题并设置适当的数据。 对于情况2,您需要填充标题布局并添加适当的数据。
如果你想以“正确”的方式完成它,而不是使用hack的方法,那么你应该编写自己的LayoutManager,并手动处理这些情况。这并不像听起来那么难,但需要一些努力。