How to give space between gridview in through java

前端 未结 3 1463
佛祖请我去吃肉
佛祖请我去吃肉 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:07

    Use Space Decoration Class For That

    public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
        private int space;
    
        public SpacesItemDecoration(int space) {
            this.space = space;
        }
    
        @Override
        public void getItemOffsets(Rect outRect, View view,
                                   RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.right = space;
            outRect.bottom = space;
    
            // Add top margin only for the first item to avoid double space between items
            if (parent.getChildLayoutPosition(view) == 0) {
                outRect.top = space;
            } else {
                outRect.top = 0;
            }
        }
    }
    

    Your Activity Where You Set Your Adapter

    int spacing = getResources().getDimensionPixelSize(R.dimen.spacing);
    
      recyclerview.addItemDecoration(new SpacesItemDecoration(spacing));
    

    Specify in dimen.xml

     5px
    

    Xml Code:

        
    
     
    
                
    
                    
                
    
    
                    
    
            
    
        
    

提交回复
热议问题