RecyclerView 設定item間隔和隨機高度
阿新 • • 發佈:2019-01-28
在瀑布流中,如果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'