android RecyclerView 中添加 FooterView 和 DividerItemDecoration 后不能正确显示的问题

来源:互联网 发布:我知谁掌管明天刘若英 编辑:程序博客网 时间:2024/06/10 23:58

今天被一个问题困扰了一个下午,在 RecyclerView 中添加 FooterView 后,由于产品需求,最后一行不能存在间隔,所以需要在 DividerItemDecoration 中将最后一行的上下两个间隔去掉,代码如下:

 public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {        if (isLastRow(view, parent) || isLastButTwoRow(view, parent)) {            outRect.set(0, 0, 0, 0);        } else {            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());        }    }    // 如果是最后一行    private boolean isLastRow(View view, RecyclerView parent) {        int position = parent.getChildAdapterPosition(view);        int count = parent.getAdapter().getItemCount();        return position == count - 1;    }    private boolean isLastButTwoRow(View view, RecyclerView parent) {        int position = parent.getChildAdapterPosition(view);        int count = parent.getAdapter().getItemCount();        return position == count - 2;    }

判断是否为倒数第一行和倒数第二行,如果是的话,则不添加间隔,但是实际情况和想象的有些差别,如下图所示:

这里写图片描述

可以看到,footer 在最后一行的上面,而且最后一行的间隔 divider 没有去掉,这个问题困扰我很久,直到我给 footer 加了一个背景颜色,如下所示

<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:orientation="vertical">    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center"        android:text="footer"        android:textSize="18sp"        android:textColor="@android:color/holo_red_dark"        android:background="@android:color/white"    /></LinearLayout>

当没有

android:background="@android:color/white"

这一句时,就出现了上面的情况,当加上这个背景时,效果如下

这里写图片描述

可以看到,FooterView 的上下两边的间隔都去掉了,从而达到了我的目的

0 0
原创粉丝点击