RecyclerView 设置item间隔和随机高度

来源:互联网 发布:网络直播运营模式 编辑:程序博客网 时间:2024/05/19 00:08

在瀑布流中,如果item中的数据格式完全相同的话,和Grid的效果相同,所以我们要为item设置一个随机的高度

一.在onBindViewHolder()中为item设置随机高度

 //修改瀑布流随机高度            Random random = new Random();            ViewGroup.LayoutParams layoutParams = holder.tv.getLayoutParams();            layoutParams.height=random.nextInt(200)+50;            holder.tv.setLayoutParams(layoutParams);

二.为item设置间隔

//RecycleView 增加边距        int spacingInPixels = 8;        mRecyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));

再添加一个增加间隔的类

 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.getChildPosition(view) == 0)                outRect.top = space;        }    }

三.在添加删除时报了一个java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v4/animation/AnimatorCompatHelper的错误
在moudle的gradle中添加如下代码:

configurations.all {    resolutionStrategy.eachDependency { DependencyResolveDetails details ->        def requested = details.requested        if (requested.group == 'com.android.support') {            if (!requested.name.startsWith("multidex")) {                details.useVersion '24.1.0'            }        }    }}

RecyclerView的依赖

compile 'com.android.support:mediarouter-v7:25.0.0'    compile 'com.android.support:appcompat-v7:25.0.0'    compile 'com.android.support:recyclerview-v7:25.0.0'
原创粉丝点击