Search code examples
androidandroid-recyclerviewstaggeredgridlayoutmanager

Order items on RecyclerView using StaggeredGridLayoutManager


I am creating an application where users create elements with an image and they are displayed as a list. It looks like Google Keep, where the elements created do not have the same height but the same width, distributed in two columns. The order in which the elements are created is important and must be arranged in that way, from top to bottom. As shown in the photo, each number represents the order in which the elements were created, it is not ordered in the expected way.

staggered view

Is there any way in which you can define how the elements should be ordered? I would like to order them:

1 2

3 4

5

and so on.

This is the code snippet where I initialize the RecyclerView, the adapter and the Layout Manager:

RecyclerView recyclerView = findViewById(R.id.recyclerView);
AdapterRecyclerView adapterRecyclerView = new AdapterRecyclerView(getContext(), list);
recyclerView.setAdapter(adapterRecyclerView );
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);

I already tried with

staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);

and it didn't work, I also tried

staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);

but it didn't show anything, just a blank layout.

Edit: any other way to do this will be apretiated, a library, another idea, etc.


Solution

  • You can try setting one value on the element that indicates the position and order the list before set it to the adapter. I recommend you use a long value and set it with System.currentTimeMillis() when the object is created so you will be sure that the value is unique and will indicate exactly when was created.