我从xml布局中获得了当前的余量,但是在所有四个方面都不一样.
如何获得相等的保证金
我目前的xml布局
android:layout_width="match_parent"
android:layout_height="300dp">
android:id="@+id/iv_photo"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_marginEnd="6dp"
android:layout_marginTop="6dp"
android:adjustViewBounds="true"
android:background="@color/colorPrimary"
android:foreground="?android:attr/selectableItemBackground"
android:scaleType="fitXY" />
解决方法:
您可以使用ItemDecoration来实现此目的
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;
}
}
}
这是你在java代码中使用它的方法
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
该解决方案由@ianhanniballake提供.希望这会帮助你.
标签:android-recyclerview,android
来源: https://codeday.me/bug/20190722/1501203.html