How to give space between gridview in through java

前端 未结 3 1427
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 18:32

How do i get perfect aligning between the gridView items, i have added the gridview using java and it\'s base adapter is set in which i added the image and textview.

Xml

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-23 19:13

    Try this,

        recyclerView  = (RecyclerView) findViewById(R.id.recyclerView );
        recyclerView .setLayoutManager(new GridLayoutManager(getActivity(), 2));
        int spanCount = 2; 
        int spacing_left = 10; 
        int spacing_top=15;
    
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing_left, spacing_top));
    

    GridSpacingItemDecoration:

        /* set spacing for grid view */
        public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
            final private int spanCount, spacing, spacing_top;
            final private boolean includeEdge;
    
            public GridSpacingItemDecoration(int spanCount, int spacing_left, int spacing_top) {
                this.spanCount = spanCount;
                this.spacing = spacing_left;
                this.includeEdge = true;
                this.spacing_top = spacing_top;
            }
    
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view); // item phases_position
                int column = position % spanCount; // item column
    
                if (includeEdge) {
                    outRect.left = spacing - column * spacing / spanCount;
                    outRect.right = (column + 1) * spacing / spanCount;
    
                    if (position < spanCount) { // top edge
                        outRect.top = spacing_top;
                    }
                    outRect.bottom = spacing_top; // item bottom
                } else {
                    outRect.left = column * spacing / spanCount; 
                    outRect.right = spacing - (column + 1) * spacing / spanCount;
                    if (position >= spanCount) {
                        outRect.top = spacing_top; // item top
                    }
                }
            }
        }
    

提交回复
热议问题