到目前为止,我一直在尝试创建一个 recyclerView,但现在我遇到了一个问题。
我需要让它看起来像这样
我需要把它变成像列表一样的网格,但是我无法将它们并排放置。
其次,如果最后一项是“单独的”,我需要最后一项来填充两个空格。
有什么想法吗?
最佳答案
I need to make it Grid like list
您可以使用 RecyclerView
和 GridLayoutManager
来实现它。例如,
// 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"
要自定义网格项目,我们可以使用ItemDecoration
。在您的情况下,最后一项如果单独存在,则应具有父级宽度。我们可以通过检查最后一项的位置来实现这一点。
现在,代码:
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;
}
}
}
关于android - 使最后一个 RecyclerView Item 填充 RecyclerView 中的空间(如果数据计数为奇数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34852162/