我正在使用RecyclerView与StaggeredGridLayoutManager来制作一个两列列表.但是如何在左列和右列之间设置一个右边距.我使用这个代码从顶部做出正确的边距,但是如何解决列之间的双重空格.
public class SpacesItemDecoration extends RecyclerView.ItemDecoration { private int space; public SpacesItemDecoration(int space) { this.space = space; } @Override public void getItemOffsets(Rect outRect,View view,RecyclerView parent,RecyclerView.State state) { outRect.left = space; outRect.right = space; outRect.bottom = space; // Add top margin only for the first or second item to avoid double space between items // Add top margin only for the first or second item to avoid double space between items if((parent.getChildCount() > 0 && parent.getChildPosition(view) == 0) || (parent.getChildCount() > 1 && parent.getChildPosition(view) == 1)) outRect.top = space; }
在活动中:
recyclerView.addItemDecoration(new SpacesItemDecoration(20));
我试图使用view.getX(),它总是返回0.
有人可以帮我吗非常感谢!
解决方法
在您的情况下,您可以将两个边距设置为RecyclerView.但在我的情况下,图像与RecyclerView中的屏幕宽度匹配,我使用ItemDecoration来解决问题.
class ViewItemDecoration extends RecyclerView.ItemDecoration { public ViewItemDecoration() { } @Override public void getItemOffsets(Rect outRect,final View view,final RecyclerView parent,RecyclerView.State state) { super.getItemOffsets(outRect,view,parent,state); int position = parent.getChildAdapterPosition(view); int spanIndex = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex(); int type = adapter.getItemViewType(position); switch(type){ case YOUR_ITEMS: if (spanIndex == 0) { outRect.left = 10; outRect.right = 5; } else {//if you just have 2 span . Or you can use (staggeredGridLayoutManager.getSpanCount()-1) as last span outRect.left = 5; outRect.right = 10; } } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。