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:
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With