您当前的位置: 首页 >  android

梁同学与Android

暂无认证

  • 3浏览

    0关注

    618博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Android --- GridLayoutManager 设置了 item 均匀分布,但是无效

梁同学与Android 发布时间:2021-05-03 12:47:14 ,浏览量:3

检查你的 item 布局的最外层是否是

android:layout_width="match_parent"

附加均匀分布的方法

// 创建布局管理

     GridLayoutManager manager = new GridLayoutManager(getContext(),2,GridLayoutManager.VERTICAL,false);
        rv_organ.addItemDecoration(new SpaceItemDecoration(0,2));
        rv_organ.setLayoutManager(manager);

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int leftRight;
        private int topBottom;

        // leftRight 为横向间的距离 topBottom为纵向间距离

        public SpaceItemDecoration(int leftRight, int topBottom) {
            this.leftRight = leftRight;
            this.topBottom = topBottom;
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            super.onDraw(c, parent, state);
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
            // 竖直方向的
            if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {
                // 最后一项需要 bottom
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.bottom = topBottom;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.right = leftRight;
            } else {
                // 最后一项需要 right
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.right = leftRight;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.bottom = topBottom;
            }
        }
    }
关注
打赏
1660730345
查看更多评论
立即登录/注册

微信扫码登录

0.0845s