RecycleView嵌套子RecycleView并且网格布局问题

2023-07-07 15:49:49 浏览数 (3)

问题:子RecycleView网格布局的话,使用GridSpacingItemDecoration控制间隔大小,不断上下滑动,部分间距会不断变大,超出界面

解决方法:

代码语言:java复制
if (holder.rlv_select.getItemDecorationCount() == 0) {
    int spacing = mContext.getResources().getDimensionPixelSize(R.dimen.dp_20);
    holder.recyclerView.addItemDecoration(new GridSpacingItemDecoration(4, spacing, false));
}

或者(未使用过)

代码语言:javascript复制
holder.recyclerView.removeItemDecoration();

附带询问AI可以得到的代码:

代码语言:javascript复制
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
    private int spanCount;
    private int spacing;
    private int topSpacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    public GridSpacingItemDecoration(int spanCount, int spacing, int topSpacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.topSpacing = topSpacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column   1) * spacing / spanCount; // (column   1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // item bottom
        } else {
            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column   1) * spacing / spanCount; // spacing - (column   1) * ((1f / spanCount) * spacing)
            if (position >= spanCount) {
                outRect.top = topSpacing; // item top
            }
        }
    }
}

0 人点赞