我正在使用 StaggeredGridLayoutManager 并且有一些接近我想要的东西。我有一个 2 行的水平交错网格,其中一些项目是 1 行的高度,而其他项目跨越两行。我希望单行高度项目堆叠起来,我认为可以通过将间隙策略设置为 GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS 来实现,但这似乎不起作用。
当前的:
___ ___ ___ ___ |___| | | |___| | | | | | | |___| |___|
我想要的是:
___ ___ ___ |___| | | | | ___ | | | | |___| |___| |___|
相关代码片段:
为 recyclerview 设置布局管理器:
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.HORIZONTAL);
layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
recyclerView.setLayoutManager(layoutManager);
这是我的自定义适配器的 onBindViewHolder(这只是一个简化的示例)。基本上我在 CardView 中有一个 ImageView(CardView 设置为 wrap_content 的高度和宽度)。
if(position%3==0) {
ViewGroup.LayoutParams layoutParams = viewHolder.myImage.getLayoutParams();
layoutParams.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, context.getResources().getDisplayMetrics());
layoutParams.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 75, context.getResources().getDisplayMetrics());
viewHolder.myImage.setLayoutParams(layoutParams);
StaggeredGridLayoutManager.LayoutParams layoutParams1 = ((StaggeredGridLayoutManager.LayoutParams) viewHolder.itemView.getLayoutParams());
layoutParams1.setFullSpan(false);
}
else {
ViewGroup.LayoutParams layoutParams = viewHolder.myImage.getLayoutParams();
layoutParams.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, context.getResources().getDisplayMetrics());
layoutParams.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, context.getResources().getDisplayMetrics());
viewHolder.myImage.setLayoutParams(layoutParams);
StaggeredGridLayoutManager.LayoutParams layoutParams1 = ((StaggeredGridLayoutManager.LayoutParams) viewHolder.itemView.getLayoutParams());
layoutParams1.setFullSpan(true);
}