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:
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.
Take a look at this. It's google library which brings the similar capabilities of CSS Flexible Box Layout Module to Android.
in Activity
in Adapter.ViewHolder
and make sure you set
android:layout_gravity="center"