android – 如何避免使用RecyclerView与StaggeredGridLayoutManager之间的项目之间的双重空间?

前端之家收集整理的这篇文章主要介绍了android – 如何避免使用RecyclerView与StaggeredGridLayoutManager之间的项目之间的双重空间?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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.

有人可以帮我吗非常感谢!

解决方法@H_502_14@
在您的情况下,您可以将两个边距设置为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;
                }
        }
    }

}

原文链接:https://www.f2er.com/android/312489.html

猜你在找的Android相关文章