【问题标题】:Android: How to have a 1 - 2 - 1 list item formation in a GridView or RecyclerView?Android:如何在 GridView 或 RecyclerView 中形成 1 - 2 - 1 列表项?
【发布时间】:2020-05-14 18:14:46
【问题描述】:

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

 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;
    }
}

【问题讨论】:

    标签: android gridview android-recyclerview


    【解决方案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());
    

    【讨论】:

    • 我应该使用GridView而不是RecyclerView吗?
    • 不,你应该使用RecyclerView
    • @KesWalker 应该。你的单元格有match_parent 作为宽度? GridLayoutManager 的方向是 VERTICAL?它的跨度大小是否为 2?
    • 好的,在将单元格宽度设置为match_parent 之后,有些视图是父视图的宽度,但有些视图是宽度的一半。这不是我所需要的。我需要两个相邻的视图,而不是一个视图占用两个视图的空间,抱歉
    • 啊,好吧,我明白了,如果我将 position % 2 == 0 ? 2 : 1 更改为 position % 3 == 0 ? 2 : 1,它会按预期执行,非常感谢 :)
    猜你喜欢
    • 2018-06-16
    • 2017-11-25
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    相关资源
    最近更新 更多