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

今天被一个问题困扰了一个下午,在 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值