Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center Horizontal last row using span Recycler GridLayoutManager

I am trying to make items of the last row center horizontal in recycler view. I am using GridLayoutManager in order to achieve the functionality. Using setSpanSizeLookup, I want to adjust span size for the last row as pointed by posts on SO, but unfortunately I can't keep track which row is currently being populated, so my logic isn't working.

What I want to achieve is:

enter image description here

Code:

static private int NUM_OF_COLUMNS = 3;

final GridLayoutManager manager = new GridLayoutManager(getBaseActivity(), NUM_OF_COLUMNS);

        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {

            int rowNum = 0;

            @Override
            public int getSpanSize(int position) {

                int spanSize = 1;

                if(position == 0)
                    rowNum = 0; //reset it

                //check if it is last row
                int numOfRows = (int) Math.ceil((double) list.size() / NUM_OF_COLUMNS);
                if(rowNum == numOfRows - 1) {
                    //get num of items in last row
                    int items = list.size() - (NUM_OF_COLUMNS * rowNum);
                    if(items == 1)
                        spanSize = 3;
                }

                if(rowNum % NUM_OF_COLUMNS == 0) //if last element
                    rowNum++;

                return spanSize;
            }
        });

        recyclerView.setLayoutManager(manager);

Above code is managing row number since I don't know how to get current row and column position for grid. Can anyone point towards right direction? Thanks.

like image 328
NightFury Avatar asked Dec 20 '16 11:12

NightFury


1 Answers

Take a look at this. It's google library which brings the similar capabilities of CSS Flexible Box Layout Module to Android.

in Activity

  FlexboxLayoutManager layoutManager = new FlexboxLayoutManager();
        layoutManager.setFlexWrap(FlexWrap.WRAP);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setAlignItems(AlignItems.CENTER);
        viewDecks.setLayoutManager(layoutManager);

in Adapter.ViewHolder

ViewGroup.LayoutParams lp = itemView.getLayoutParams();
            if (lp instanceof FlexboxLayoutManager.LayoutParams) {
                FlexboxLayoutManager.LayoutParams flexboxLp = (FlexboxLayoutManager.LayoutParams) lp;
                flexboxLp.setFlexGrow(1.0f);
                flexboxLp.setAlignSelf(AlignSelf.CENTER);
            }

and make sure you set android:layout_gravity="center"

like image 182
svkaka Avatar answered Sep 19 '22 06:09

svkaka