在我的Android应用中,我使用<uses-permission android:name="android.permission.INTERNET" />
使用RecyclerView
在网格中显示项目。
在GridView中,为了指定元素之间的间距,我将设置 horizontalSpacing 和 verticalSpacing 属性。
那么,我怎样才能在GridLayoutManager
上做同样的事情?
答案 0 :(得分:17)
我还没有使用GridLayout对其进行测试,但对于LinearLayout,我只是为每个列表项的根布局设置了一个边距。我想如果你想在所有项目之间保持相同的空间(让我们说8dp),你必须这样做:
这样你就可以在每个项目周围保持8 dp。
下面的代码是一个水平的RecyclerView,它显示正确间距为8 dp的图像:
<!-- fragment_layout.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
tools:listitem="@layout/list_item" />
</LinearLayout>
<!-- list_item.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp">
<ImageView
android:layout_width="@dimen/thumbnail_size"
android:layout_height="@dimen/thumbnail_size"
android:contentDescription="@string/image_content_desc" />
</LinearLayout>
编辑:我意识到项目视图需要有一个父ViewGroup,所以我更新了代码片段。
答案 1 :(得分:5)
你必须使用ItemDecorator
:
public class EqualSpaceItemDecoration extends RecyclerView.ItemDecoration {
private final int mSpaceHeight;
public EqualSpaceItemDecoration(int mSpaceHeight) {
this.mSpaceHeight = mSpaceHeight;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
RecyclerView.State state) {
outRect.bottom = mSpaceHeight;
outRect.top = mSpaceHeight;
outRect.left = mSpaceHeight;
outRect.right = mSpaceHeight;
}
}
答案 2 :(得分:0)
public class EqualSpaceItemDecoration extends RecyclerView.ItemDecoration {
private final int mSpaceHeight;
public EqualSpaceItemDecoration(int mSpaceHeight) {
this.mSpaceHeight = mSpaceHeight;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
RecyclerView.State state) {
outRect.bottom = mSpaceHeight;
outRect.top = mSpaceHeight;
outRect.left = mSpaceHeight;
outRect.right = mSpaceHeight;
}
上述答案将产生图像相遇的不等边距宽度。
以下解决方案产生均匀的利润
public void getItemOffsets (Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position= parent.getChildAdapterPosition (view);
int column = position% numberOfColumns;
outRect.left= margin-column*spacingPx/numberOfColumns;
outRect.right= (column+1)* margin/numberOfColumns;
outRect.top= margin;
}
}