I need to make it Grid like list
You can acheive it using RecyclerView
with GridLayoutManager
. For example,
// Initialize the view
recyclerView=(RecyclerView)findViewById(R.id.recyclerView);
// Here 2 is the number of columns
GridLayoutManager llm = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(llm);
recyclerView.setHasFixedSize(true);
I need the last item to fill both spaces if the last item is "alone"
To customize the grid items, we can use ItemDecoration
. And in your case, the last item if it is alone should have the parent width. We can acheive this by checking the position of the last item.
Now, the code:
In Activity
recyclerView=(RecyclerView)findViewById(R.id.recyclerView);
GridLayoutManager llm = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(llm);
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new GridItemDecoration());
// And set adapter
GridItemDecoration.java
public class GridItemDecoration extends RecyclerView.ItemDecoration
{
private int mHorizontalSpacing = 10;
private int mVerticalSpacing = 10;
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
{
super.getItemOffsets(outRect, view, parent, state);
// Only handle the vertical situation
int position = parent.getChildPosition(view);
if (parent.getLayoutManager() instanceof GridLayoutManager)
{
GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
int spanCount, column;
// Check the last item and is alone. Then set the parent's width
if (position == parent.getAdapter().getItemCount() - 1 && position % 2 == 0)
{
spanCount = 1;
outRect.left = mHorizontalSpacing;
outRect.right = parent.getWidth() - mHorizontalSpacing;
}
else
{
spanCount = layoutManager.getSpanCount();
column = position % spanCount;
outRect.left = mHorizontalSpacing * (spanCount - column) / spanCount;
outRect.right = mHorizontalSpacing * (column + 1) / spanCount;
}
if (position < spanCount)
{
outRect.top = mVerticalSpacing;
}
outRect.bottom = mVerticalSpacing;
}
}
}