当前位置 : 主页 > 编程语言 > java >

RecyclerView使用GridLayoutManager时的自定义间隔Decoration

来源:互联网 收集:自由互联 发布时间:2021-06-28
gistfile1.txt /** * RecyclerView的间距类 */ class MyGridItemDecoration extends RecyclerView.ItemDecoration { /** * @param outRect 边界 * @param view recyclerView ItemView * @param parent recyclerView * @param state recycler 内部数据
gistfile1.txt
/**
     * RecyclerView的间距类
     */
    class MyGridItemDecoration extends RecyclerView.ItemDecoration {
        /**
         * @param outRect 边界
         * @param view    recyclerView ItemView
         * @param parent  recyclerView
         * @param state   recycler 内部数据管理
         */
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            //设定底部边距为1px

            //当前位置
            int position = parent.getChildAdapterPosition(view);
            RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
            //列数
            int spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
            //总数
            int itemCount = parent.getAdapter().getItemCount();

            if(!isLastLine(position, spanCount, itemCount)) {
                outRect.set(0, 0, 0, CommonUtils.dip2px(getActivity(), 26));
            }
        }

        /**
         * 是否是最后一行
         * @param position 位置
         * @param spanCount 列数
         * @param itemCount 总数
         */
        private boolean isLastLine(int position, int spanCount, int itemCount) {
            int maxLine;
            if(itemCount % spanCount == 0) {
                maxLine = itemCount / spanCount;
            } else {
                maxLine = itemCount / spanCount + 1;
            }

            int posLine;
            if((position + 1) % spanCount == 0) {
                posLine = (position + 1) / spanCount;
            } else {
                posLine = (position + 1) / spanCount + 1;
            }

            if(posLine == maxLine) {
                return true;
            } else {
                return false;
            }

        }
    }
网友评论