我正在尝试在StaggeredGrid中实现自定义Rowspan
如何动态更改StaggeredGridLayout的行距。 @Gabriele Mariotti提出了一个实现
StaggeredGridLayoutManager.LayoutParams layoutParams =StaggeredGridLayoutManager.LayoutParams) viewHolder.itemView.getLayoutParams();
layoutParams.setFullSpan(true);
但我无法让它发挥作用。请建议我实现此目的的一些方法。
以下是我的Adapter Class的代码,它将Recycler Adapter与View holder类一起扩展为嵌套类
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
LayoutInflater inflater;
Context context;
List<Information> data= Collections.emptyList();
public MyAdapter(Context context,List<Information>data)
{
inflater= LayoutInflater.from(context);
this.context=context;
this.data=data;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.custom_layout,parent,false);
MyViewHolder holder=new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current=data.get(position);
holder.imageView.setImageResource(current.iconid);
if(position==0) {
StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
layoutParams.setFullSpan(true);
}
}
@Override
public int getItemCount() {
return 8;
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
public MyViewHolder(View itemView) {
super(itemView);
imageView= (ImageView) itemView.findViewById(R.id.image);
}
}
}
答案 0 :(得分:0)
您可以尝试使用此代码,这将在示例图像中创建第一个项目跨越两列的布局:
// Create a grid layout with two columns
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
// Create a custom SpanSizeLookup where the first item spans both columns
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
return position == 0 ? 2 : 1;
}
});
recyclerView.setLayoutManager(layoutManager);
示例图片中的项目看起来不会错开,所以这会使用常规的2列GridLayoutManager
。我不确定如何使用StaggeredGridLayoutManager
,但请试一试。