RecycerView 单独设置每个childView的间隔--使用ItemDecoration

public class SpacingItemDecoration extends RecyclerView.ItemDecoration {
        private int halfSpaceInPx;

        public SpacingItemDecoration(int horizontalSpaceInPx) {
            halfSpaceInPx = (int) (0.5f * horizontalSpaceInPx);
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);

            if (parent != null) {
//                int childIndex=parent.getChildPosition(view);//deprecated
                int childIndex = parent.getChildAdapterPosition(view);
                RecyclerView.Adapter adapter = parent.getAdapter();
                if (adapter != null) {
                    int childCount = adapter.getItemCount();
                    outRect.left = halfSpaceInPx;
                    outRect.right = halfSpaceInPx;
                    if (childIndex == 0) {//the first one,第一个,左边缘间距
                        outRect.left = SystemUtil.dpToPx(12);//12dp;
                    }
                    if (childIndex == childCount - 1) {//the last one,最后一个,右边缘间距
                        outRect.right = SystemUtil.dpToPx(12);//12dp
                    }

                    Loger.d(TAG, "--->getItemOffsets()--childIndex:" + childIndex + ",childCount=" + childCount);
                }
            }
        }
    }


使用如下代码添加:

mRecyclerView.addItemDecoration(new SpacingItemDecoration(SystemUtil.dpToPx(10)));//间隔为10dp


你可能感兴趣的:(Android)