想要在不使用cardUseCompatPadding的情况下在CardView卡之间添加间距,我该如何实现?
答案 0 :(得分:2)
在行上设置填充,以便所有项目在每个项目之间设置间距
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#FFF"
android:padding="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
// here your views
</LinearLayout>
或者,通过java使用这样来分配项目
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setItemAnimator(new DefaultItemAnimator());
int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
recyclerView.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.getChildLayoutPosition(view) == 0) {
outRect.top = space;
} else {
outRect.top = 0;
}
}
}
答案 1 :(得分:0)
如果您使用数据绑定,您可能更喜欢检查列表项中的 <Space />
组件水平 RecyclerView
间距
如下所示;
<data>
<variable
name="data"
type="com.foo.Entity" />
<variable
name="position"
type="int" />
<import type="android.view.View" />
</data>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="45dp"
android:gravity="center"
android:orientation="horizontal">
<Space
android:layout_width="6dp"
android:layout_height="6dp"
android:visibility="@{position == 0 ? View.GONE : View.VISIBLE}" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/gray_border">
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_margin="8dp"
android:background="@color/white"
android:gravity="center"
android:lineSpacingExtra="4sp"
android:maxLines="1"
android:singleLine="true"
android:text="@{data.text}"
android:textColor="#6b778d"
android:textSize="12sp"
android:textStyle="normal"
tools:text="Foo" />
</RelativeLayout>
</LinearLayout>
你会看到;