Jay*_*iyk 5 android gridlayoutmanager android-recyclerview linearlayoutmanager
到目前为止我一直在尝试创建一个recyclerView,但现在我遇到了一个问题。
我需要让它看起来像这样
我需要将其设置为类似网格的列表,但是我无法将它们并排放置。
其次,如果最后一项是“单独的”,我需要最后一项来填充两个空格。
有任何想法吗?
我需要将其做成类似网格的列表
您可以使用RecyclerViewwith来实现它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);
Run Code Online (Sandbox Code Playgroud)
如果最后一项是“单独的”,我需要最后一项来填充两个空格
要自定义网格项,我们可以使用ItemDecoration. 在您的情况下,最后一项(如果单独)应该具有父宽度。我们可以通过检查最后一项的位置来实现这一点。
现在,代码:
活动中
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
Run Code Online (Sandbox Code Playgroud)
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2296 次 |
| 最近记录: |