如何在 recyclerview 中实现粘性页脚

How implement sticky footer in recyclerview

我有 RecyclerView,我需要下一个行为:

请告知我如何实现此行为。

如果您不能忘记 RecyclerView 而使用 ListView,那么请检查这个 link Is there an addHeaderView equivalent for RecyclerView? 它拥有您需要的一切。它是关于页眉的,但几乎相同,只是页眉在列表的开头,页脚在结尾。

我知道,这是一个老问题,但我会为那些将来会搜索此类决定的人添加一个答案。 可以 将最后一个项目保留在屏幕底部,以防你只有很少或没有项目,并在你有很多项目时使最后一个项目与 recyclerview 一起滚动。

如何实现。您的 RecyclerView 适配器应应用多种视图类型:视图,应显示为列表项;视图,应显示为页脚;一个空的视图。您可以在此处查看如何将具有不同视图的项目放入 RecyclerView: 在主列表和页脚视图之间找到一个空视图。 然后在空视图的 onBindViewHolder 中检查您的主列表视图和页脚视图是否占据所有屏幕。如果是 - 将空视图高度设置为零,否则将其设置为项目和页脚似乎未采用的高度。就这样。 当您 delete/add 行时,您也可以动态更新该高度。更新列表后,只需为空的 space 项目调用 notifyItemChanged。

您还需要将 RecyclerView 高度设置为 match_parent 或精确高度,而不是 wrap_content!

希望对您有所帮助。

您可以使用 RecyclerView.ItemDecoration 来实现此行为。

public class StickyFooterItemDecoration extends RecyclerView.ItemDecoration {

    /**
     * Top offset to completely hide footer from the screen and therefore avoid noticeable blink during changing position of the footer.
     */
    private static final int OFF_SCREEN_OFFSET = 5000;

    @Override
    public void getItemOffsets(Rect outRect, final View view, final RecyclerView parent, RecyclerView.State state) {
        int adapterItemCount = parent.getAdapter().getItemCount();
        if (isFooter(parent, view, adapterItemCount)) {
            //For the first time, each view doesn't contain any parameters related to its size,
            //hence we can't calculate the appropriate offset.
            //In this case, set a big top offset and notify adapter to update footer one more time.
            //Also, we shouldn't do it if footer became visible after scrolling.
            if (view.getHeight() == 0 && state.didStructureChange()) {
                hideFooterAndUpdate(outRect, view, parent);
            } else {
                outRect.set(0, calculateTopOffset(parent, view, adapterItemCount), 0, 0);
            }
        }
    }

    private void hideFooterAndUpdate(Rect outRect, final View footerView, final RecyclerView parent) {
        outRect.set(0, OFF_SCREEN_OFFSET, 0, 0);
        footerView.post(new Runnable() {
            @Override
            public void run() {
                parent.getAdapter().notifyDataSetChanged();
            }
        });
    }

    private int calculateTopOffset(RecyclerView parent, View footerView, int itemCount) {
        int topOffset = parent.getHeight() - visibleChildsHeightWithFooter(parent, footerView, itemCount);
        return topOffset < 0 ? 0 : topOffset;
    }

    private int visibleChildsHeightWithFooter(RecyclerView parent, View footerView, int itemCount) {
        int totalHeight = 0;
        //In the case of dynamic content when adding or removing are possible itemCount from the adapter is reliable,
        //but when the screen can fit fewer items than in adapter, getChildCount() from RecyclerView should be used.
        int onScreenItemCount = Math.min(parent.getChildCount(), itemCount);
        for (int i = 0; i < onScreenItemCount - 1; i++) {
            totalHeight += parent.getChildAt(i).getHeight();
        }
        return totalHeight + footerView.getHeight();
    }

    private boolean isFooter(RecyclerView parent, View view, int itemCount) {
        return parent.getChildAdapterPosition(view) == itemCount - 1;
    }
}

确保为 RecyclerView 高度设置 match_parent

请查看示例应用程序 https://github.com/JohnKuper/recyclerview-sticky-footer and how it works http://sendvid.com/nbpj0806

此解决方案的一个巨大缺点是它只有在整个应用程序(不是内部装饰)中的 notifyDataSetChanged() 之后才能正常工作。对于更具体的通知,它将无法正常工作并支持它们,它需要更多的逻辑方式。此外,您可以通过 eowise 从库 recyclerview-stickyheaders 中获得见解并改进此解决方案。

我正在使用带权重的线性布局。我为页脚重量创建了多个值,效果很好。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:background="@color/white"
    android:orientation="vertical"

<include layout="@layout/header" />

    <android.support.v7.widget.RecyclerView
    android:id="@+id/recycleView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.5"
    tools:layout_height="0dp"
    tools:listitem="@layout/row" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="@dimen/footer_weight"
    android:padding="@dimen/extra_padding"
    android:paddingEnd="@dimen/small_padding"
    android:paddingLeft="@dimen/small_padding"
    android:paddingRight="@dimen/small_padding"
    android:paddingStart="@dimen/small_padding"
    android:text="@string/contact"
    android:textColor="@color/grey" />

 </LinearLayout>

改进Dmitriy Korobeynikov并解决调用通知数据集的问题已更改

public class StickyFooterItemDecoration extends RecyclerView.ItemDecoration {

  @Override
  public void getItemOffsets(Rect outRect, final View view, final RecyclerView parent,
      RecyclerView.State state) {

    int position = parent.getChildAdapterPosition(view);
    int adapterItemCount = parent.getAdapter().getItemCount();
    if (adapterItemCount == RecyclerView.NO_POSITION || (adapterItemCount - 1) != position) {
      return;
    }
    outRect.top = calculateTopOffset(parent, view, adapterItemCount);
  }


  private int calculateTopOffset(RecyclerView parent, View footerView, int itemCount) {
    int topOffset =
        parent.getHeight() - parent.getPaddingTop() - parent.getPaddingBottom()
            - visibleChildHeightWithFooter(parent, footerView, itemCount);
    return topOffset < 0 ? 0 : topOffset;
  }



  private int visibleChildHeightWithFooter(RecyclerView parent, View footerView, int itemCount) {
    int totalHeight = 0;
    int onScreenItemCount = Math.min(parent.getChildCount(), itemCount);
    for (int i = 0; i < onScreenItemCount - 1; i++) {
      RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) parent.getChildAt(i)
          .getLayoutParams();
      int height =
          parent.getChildAt(i).getHeight() + layoutParams.topMargin
              + layoutParams.bottomMargin;
      totalHeight += height;
    }
    int footerHeight = footerView.getHeight();
    if (footerHeight == 0) {
      fixLayoutSize(footerView, parent);
      footerHeight = footerView.getHeight();
    }
    footerHeight = footerHeight + footerView.getPaddingBottom() + footerView.getPaddingTop();

    return totalHeight + footerHeight;
  }

  private void fixLayoutSize(View view, ViewGroup parent) {
    // Check if the view has a layout parameter and if it does not create one for it
    if (view.getLayoutParams() == null) {
      view.setLayoutParams(new ViewGroup.LayoutParams(
          ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    }

    // Create a width and height spec using the parent as an example:
    // For width we make sure that the item matches exactly what it measures from the parent.
    //  IE if layout says to match_parent it will be exactly parent.getWidth()
    int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getWidth(), View.MeasureSpec.EXACTLY);
    // For the height we are going to create a spec that says it doesn't really care what is calculated,
    //  even if its larger than the screen
    int heightSpec = View.MeasureSpec
        .makeMeasureSpec(parent.getHeight(), View.MeasureSpec.UNSPECIFIED);

    // Get the child specs using the parent spec and the padding the parent has
    int childWidth = ViewGroup.getChildMeasureSpec(widthSpec,
        parent.getPaddingLeft() + parent.getPaddingRight(), view.getLayoutParams().width);
    int childHeight = ViewGroup.getChildMeasureSpec(heightSpec,
        parent.getPaddingTop() + parent.getPaddingBottom(), view.getLayoutParams().height);

    // Finally we measure the sizes with the actual view which does margin and padding changes to the sizes calculated
    view.measure(childWidth, childHeight);

    // And now we setup the layout for the view to ensure it has the correct sizes.
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
  }
}

所有这些解决方案都不起作用。当您最小化应用程序并再次打开它时,页脚会飞到屏幕底部以下,您需要滚动才能看到它,即使只有 1-2 个项目。 您可以在 xml.

中的回收站视图下方添加页脚视图
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
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:background="@android:color/white">

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:overScrollMode="never"
    android:scrollbars="none">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

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

        <android.support.v4.widget.Space
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:minHeight="1dp" />

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <include layout="@layout/recyclerView_footer" />
        </FrameLayout>
    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

注意 - 我将 NestedScrollView 与

一起使用
    recyclerView.isNestedScrollingEnabled = false

SpaceView has weight 1 and height = 0dp 以及 linear layoutNestedScrollView has height = match_parent 中的所有这些东西,现在我的页脚贴在底部,当列表变大时它会进一步移动

class FooterViewHolder(private val parent: ViewGroup) {

...

fun bind(item: Item) {
    ...
    itemView.post(::adjustTop)
}

private fun adjustTop() {
    val parent = parent as RecyclerView
    var topOffset = parent.height
    for (child in parent.children) topOffset -= child.height
    (itemView.layoutParams as ViewGroup.MarginLayoutParams)
        .setMargins(0, topOffset.coerceAtLeast(0), 0, 0)
}
}

所选答案有误。我已经对此发表评论并解释了原因。如果你感兴趣,你可能想读一读。

所以如果选择的答案是错误的,有什么不同的更好的方法来解决这个问题?

1) 像这样创建布局:

<ConsraintLayout>
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <-- This is your footer and it can be anything you want -->
    <TextView
        android:id="@+id/yourFooter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

</ConstraintLayout>

2) 将页脚的高度设置为 RecyclerView 的 bottomPadding。在 preDraw 上执行此操作至关重要,这样您就可以拥有合适的页脚高度或尺寸。

view.doOnPreDraw {
    val footerheight = yourFooter.height
    recyclerView.updatePadding(bottom = footerHeight)
    ...
}

3) 现在您需要做的就是收听 recyclerview 滚动,并在您需要在正确的时间翻译页脚时收听。所以做这样的事情:

view.doOnPreDraw {
    val footerheight = yourFooter.height
    recyclerView.updatePadding(bottom = footerHeight)

    recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            val range = recyclerView.computeVerticalScrollRange()
            val extent = recyclerView.computeVerticalScrollExtent()
            val offset = recyclerView.computeVerticalScrollOffset()
            val threshHold = range - footerHeight
            val currentScroll = extent + offset
            val excess = currentScroll - threshHold
            yourFooter.transalationX = if (excess > 0)
                footerHeight * (excess.toFloat()/footerHeight.toFloat()) else 0F
        }
    })
}

希望这对以后的人有所帮助。