使用 GridLayoutManager 在 RecyclerView 中自定义 view/row
Custom view/row in RecyclerView with GridLayoutManager
我已经使用 GirdLayoutManager
成功实现了 RecyclerView
(普通实现,没什么特别的)但现在我卡住了,因为我想在第一个之后添加自定义 view/row 3个元素。
见下图(蓝色区域):
我怎样才能做到这一点?有任何想法吗?谢谢!
如下所示设置您的网格布局管理器:
final GridLayoutManager mng_layout = new GridLayoutManager(this.getActivity(), 2);
mng_layout.setSpanSizeLookup( new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch( recyclerAdapter.getItemViewType(position) ) {
case MyRecyclerAdapter.TYPE_SINGLE:
return 1;
case MyRecyclerAdapter.TYPE_DEFAULT:
return 2;
default:
return -1;
}
}
});
myRecyclerView.setLayoutManager(mng_layout);
然后按如下方式更新您的 RecyclerViewAdapter:
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
if (viewType==TYPE_DEFAULT) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_grid_view_item, parent, false);
return new DefaultViewHolder(view);
} else if (viewType==TYPE_SINGLE){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_grid_view_header, parent, false);
return new SingleItemViewHolder(view);
}
throw new RuntimeException("There is no type that matches the type " + viewType + " + make sure your using types correctly");
}
@Override
public int getItemViewType(int position) {
return (list.get(position).getType()==TYPE_DEFAULT) ? TYPE_DEFAULT : TYPE_SINGLE;
}
我已经使用 GirdLayoutManager
成功实现了 RecyclerView
(普通实现,没什么特别的)但现在我卡住了,因为我想在第一个之后添加自定义 view/row 3个元素。
见下图(蓝色区域):
我怎样才能做到这一点?有任何想法吗?谢谢!
如下所示设置您的网格布局管理器:
final GridLayoutManager mng_layout = new GridLayoutManager(this.getActivity(), 2);
mng_layout.setSpanSizeLookup( new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch( recyclerAdapter.getItemViewType(position) ) {
case MyRecyclerAdapter.TYPE_SINGLE:
return 1;
case MyRecyclerAdapter.TYPE_DEFAULT:
return 2;
default:
return -1;
}
}
});
myRecyclerView.setLayoutManager(mng_layout);
然后按如下方式更新您的 RecyclerViewAdapter:
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
if (viewType==TYPE_DEFAULT) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_grid_view_item, parent, false);
return new DefaultViewHolder(view);
} else if (viewType==TYPE_SINGLE){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_grid_view_header, parent, false);
return new SingleItemViewHolder(view);
}
throw new RuntimeException("There is no type that matches the type " + viewType + " + make sure your using types correctly");
}
@Override
public int getItemViewType(int position) {
return (list.get(position).getType()==TYPE_DEFAULT) ? TYPE_DEFAULT : TYPE_SINGLE;
}