其他分享
首页 > 其他分享> > Android 开发 RecyclerView设置间距

Android 开发 RecyclerView设置间距

作者:互联网

实现步骤

  1.   首先要创建一个类继承RecyclerView.ItemDecoration
  2.   然后重新这个类的getItemOffsets方法,删除方法里的super.getItemOffsets(outRect, view, parent, state);
  3.   在outRect里的属性分别设置对应方向间隔
  4.   在activity里new一个我们继承重写好的类,然后在mRecyclerView.addItemDecoration(new Divider);导入

设置全部item的间距例子  

public class RecyclerViewSpacesItemDecoration extends RecyclerView.ItemDecoration {

   private HashMap<String, Integer> mSpaceValueMap;

   public static final String TOP_DECORATION = "top_decoration";
   public static final String BOTTOM_DECORATION = "bottom_decoration";
   public static final String LEFT_DECORATION = "left_decoration";
   public static final String RIGHT_DECORATION = "right_decoration";

   public RecyclerViewSpacesItemDecoration(HashMap<String, Integer> mSpaceValueMap) {
       this.mSpaceValueMap = mSpaceValueMap;
   }

   @Override
   public void getItemOffsets(Rect outRect, View view,
                              RecyclerView parent, RecyclerView.State state) {
       if (mSpaceValueMap.get(TOP_DECORATION) != null)
           outRect.top = mSpaceValueMap.get(TOP_DECORATION);
       if (mSpaceValueMap.get(LEFT_DECORATION) != null)
           outRect.left = mSpaceValueMap.get(LEFT_DECORATION);
       if (mSpaceValueMap.get(RIGHT_DECORATION) != null)
           outRect.right = mSpaceValueMap.get(RIGHT_DECORATION);
       if (mSpaceValueMap.get(BOTTOM_DECORATION) != null)
           outRect.bottom = mSpaceValueMap.get(BOTTOM_DECORATION);

   }

}

判断并且设置特定位置item的间距的例子

public class TLeaveItemDivider extends RecyclerView.ItemDecoration {

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        if (parent.getChildAdapterPosition(view) == state.getItemCount()-1){//判断是不是最后一个item
            outRect.top = 0;
            return;

        }else {
            outRect.top = UnitConversionUtil.dip2px(parent.getContext(),15);
        }
    }
}

导入方法

mRecyclerView.addItemDecoration(new TLeaveItemDivider());

 

标签:outRect,间距,get,mSpaceValueMap,DECORATION,Android,RecyclerView,public
来源: https://www.cnblogs.com/guanxinjing/p/10443500.html