这是之前在ListView类中使用divider和dividerHeight参数实现的一个例子:
<ListView
android:id="@+id/activity_home_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@android:color/transparent"
android:dividerHeight="8dp"/>
然而,在RecyclerView类中我没有看到这样的可能性。
<android.support.v7.widget.RecyclerView
android:id="@+id/activity_home_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"/>
在这种情况下,是否可以定义边距和/或直接添加自定义分隔符视图到列表项的布局中,或者是否有更好的方法来实现我的目标?
以下是我的偷懒方法,但它很有效:
将CardView包装在一个布局中,并在父布局上设置一个填充/边距来模拟分隔符,并强制将普通分隔符设置为null。
文件list_item.xml
<LinearLayout
android:id="@+id/entry_item_layout_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="<divider_size>" > // This is the divider
<CardView
android:layout_width="<width_size>"
android:layout_height="<height_size>">
...
</CardView>
</LinearLayout
文件list.xml
<RecyclerView
android:divider="@null"
android:layout_width="<width_size>"
android:layout_height="<height_size>"
...
/>
public class VerticalItemDecoration extends RecyclerView.ItemDecoration {
private boolean verticalOrientation = true;
private int space = 10;
public VerticalItemDecoration(int value, boolean verticalOrientation) {
this.space = value;
this.verticalOrientation = verticalOrientation;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
RecyclerView.State state) {
// Skip first item in the list
if (parent.getChildAdapterPosition(view) != 0) {
if (verticalOrientation) {
outRect.set(space, 0, 0, 0);
} else if (!verticalOrientation) {
outRect.set(0, space, 0, 0);
}
}
}
}
mCompletedShippingRecyclerView.addItemDecoration(new VerticalItemDecoration(20,false));