编程语言
首页 > 编程语言> > 一对一视频聊天app源码,自定义RecyclerView间距

一对一视频聊天app源码,自定义RecyclerView间距

作者:互联网

一对一视频聊天app源码,自定义RecyclerView间距

/**
 * 自定义recyclerView间距,(上下左右都一样间距)
 * @author 2216264142@qq.com
 **/
public class CustomizeItemDecoration extends RecyclerView.ItemDecoration {
    /**
     * 间距大小
     */
    float space;
    /**
     * 排列数量
     */
    int count;

    public CustomizeItemDecoration(float space,int count) {
        this.space = space;
        this.count = count;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        //数据下标,由0开始
        int position = parent.getChildAdapterPosition(view);
        //头部
        outRect.top = dip2px(parent.getContext(),space);
        //右边
        outRect.right = dip2px(parent.getContext(),space);
        if (position % count == 0) {
            //左边
            outRect.left = dip2px(parent.getContext(),space);
        }
    }

     /**
     * dp转成px
     * @param context 上下文
     * @param dpSize 大小
     * @return px大小
     */
    private int dip2px(Context context, float dpSize) {
        final float density = context.getResources().getDisplayMetrics().density;
        return (int) (dpSize * density + 0.5f);
    }
}
 

如果想要第一行间距为0:把 CustomizeItemDecoration 中 outRect.top = dip2px(parent.getContext(),space); 换成以下代码

 //(头部一行没有设置间距)
if (position>count-1){
           outRect.top = dip2px(parent.getContext(),space);
}
 

使用方法:(RecyclerView recyclerView)

//在addItemDecoration()里面new就好
recyclerView.addItemDecoration(new CustomizeItemDecoration(5f,2));

以上就是 一对一视频聊天app源码,自定义RecyclerView间距,更多内容欢迎关注之后的文章

标签:count,outRect,自定义,parent,space,dip2px,app,源码,RecyclerView
来源: https://blog.csdn.net/yb1314111/article/details/115373036