如何使用GridLayoutManager在RecyclerView中移除行之间的间距

5
我正在尝试使用GridLayoutManager来创建一个全屏网格布局的RecyclerView。但是出现了一个问题,每行之间和RecyclerView的顶部和底部之间都添加了一定的水平间距,我无法去掉它。我搜索了解决方案并尝试了设置尺寸为0的ItemDecorator,但没有用。其他方法也无效。

图片链接

我的ItemDecorator代码非常标准,如下所示:

private class RecyclerViewItemDecorator extends RecyclerView.ItemDecoration {
    private int spaceInPixels;

    public RecyclerViewItemDecorator(int spaceInPixels) {
        this.spaceInPixels = spaceInPixels;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view,
                               RecyclerView parent, RecyclerView.State state) {
        outRect.left = spaceInPixels;
        outRect.right = spaceInPixels;
        outRect.bottom = spaceInPixels;
        if (parent.getChildLayoutPosition(view) == 0) {
            outRect.top = spaceInPixels;
        } else {
            outRect.top = 0;
        }
    }
}

这是我使用的页面布局文件。 /layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.korah.moviesapp.MainActivity">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/main_fragment"
        android:name="com.example.korah.moviesapp.MainActivityFragment"
        tools:layout="@layout/activity_main_fragment"
        >
    </fragment>

</RelativeLayout>

/layout/activity_main_fragment.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.RecyclerView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/movies_recycler"
    xmlns:android="http://schemas.android.com/apk/res/android">    
    </android.support.v7.widget.RecyclerView>

/layout/activity_movies_grid.xml

<?xml version="1.0" encoding="utf-8"?>

<ImageView
    android:id="@+id/imageView"
    android:src="@drawable/interst"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android" />

尝试为ImageView设置scaleType="fitXY"吗? - Sujay
是的兄弟!!!你真是救星,把它作为答案,我会接受它。 - Courtney
1个回答

3
应该是由于图像的缩放而不是其他原因。因此,请尝试将ImageView的scaleType设置为fitXY。
<ImageView
    android:id="@+id/imageView"
    android:src="@drawable/interst"
    android:layout_width="wrap_content"
    android:scaleType="fitXY"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接