Android: 如何在 GridView 或 RecyclerView 中形成 1 - 2 - 1 列表项?

Android: How to have a 1 - 2 - 1 list item formation in a GridView or RecyclerView?

我正在尝试在回收站或网格视图中实现以下列表项形成:

 1
1 1
 1
1 1
 1

其中 1 是单个视图持有者(列表项)。我的列表项都具有相同的宽度和高度。

我尝试将 recyclerview 与网格布局管理器一起使用,如下所示:

recyclerView.setLayoutManager(new GridLayoutManager(getContext(),2));

但这将严格显示 2 列。

我已经尝试将 StaggeredGridLayoutManager 与我的 recyclerView 一起使用,如下所示:

StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);

但这只会拉伸我的列表项以适应 2 列列表,类似于 GridLayoutManager。 我也曾尝试更改适配器中 3 个列表视图中 1 个的宽度,但一个视图的宽度不会影响另一个视图的位置。

当前设置如下所示:

    adapterPre = new CategoryListAdapter(this, getContext(),GeneralUtils.isLoggedIn());
    RecyclerView premadeLists = view.findViewById(R.id.practise_recycler);
    GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(),2);
    gridLayoutManager.setSpanSizeLookup(new CustomSpanSizeLookup());
    premadeLists.setLayoutManager(gridLayoutManager);
    premadeLists.setHasFixedSize(false);
    premadeLists.setAdapter(adapterPre);

CustomSpanSizeLookup:

class CustomSpanSizeLookup extends GridLayoutManager.SpanSizeLookup {
    @Override
    public int getSpanSize(int position) {
        return position % 2 == 0 ? 2 : 1;
    }
}

您必须使用具有 2 个跨度的 GridLayoutManager 并创建自定义 GridLayoutManager.SpanSizeLookup:

class CustomSpanSizeLookup extends GridLayoutManager.SpanSizeLookup {
    @Override
    public int getSpanSize(int position) {
        /* one in three items will occupy the whole row, 
        * two in three items will take up half a row and can 
        * therefore be placed next to each other.
        */
        return position % 3 == 0 ? 2 : 1;
    }
}

您可以在 GridLayoutManager 上使用以下方法设置它:

layoutManager.setSpanSizeLookup(new CustomSpanSizeLookup());