【问题标题】:How to add space between items only on scrolling如何仅在滚动时在项目之间添加空格
【发布时间】:2018-03-23 17:05:00
【问题描述】:

我有全屏显示的水平 RecyclerView。 这是我的活动布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/photos_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

ViewHolder 也全屏显示。

项目布局:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true">

    <ImageView
        android:id="@+id/item_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</FrameLayout>

结果我在屏幕上有一项 RecyclerView。这是我需要的。 但我不明白如何在滚动项目之间添加间距(如何在所有图片库应用程序上)。但我不需要在滚动端看到这个空间。

我如何初始化 RecyclerView:

RecyclerView photoList = findViewById(R.id.photos_list);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
        photoList.setLayoutManager(linearLayoutManager);


        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(photoList);

        PhotoListAdapter photoListAdapter = new PhotoListAdapter(this, photoResults);
        photoList.setAdapter(photoListAdapter);

在屏幕截图上,我显示了我想要得到的空间:

【问题讨论】:

    标签: android android-recyclerview


    【解决方案1】:

    要获得这个空间,您应该使用DividerItemDecoration。您可以设置它的宽度和颜色。例如,

    可绘制

     <shape xmlns:android="http://schemas.android.com/apk/res/android"
               android:shape="rectangle">
            <size
                android:width="1dp"
                android:height="1dp" />
            <solid android:color="@color/primary" />
        </shape>
    

    然后在recycler没有像这样空闲的时候再设置

    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getContext(),
                        LinearLayoutManager.VERTICAL);//or HORIZONTAL
    dividerItemDecoration.setDrawable(getContext().getResources().getDrawable(R.drawable.sk_line_divider));
    recyclerView.addItemDecoration(dividerItemDecoration);
    

    或在回收站空闲时像这样删除

    recyclerView.removeItemDecoration(dividerItemDecoration);
    

    要检测回收器是否正在滚动,请实现RecyclerView.OnScrollListener docs

    【讨论】: