您的位置:首页 > 移动开发 > Android开发

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

2016-12-08 20:17 621 查看
今天被一个问题困扰了一个下午,在 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 的上下两边的间隔都去掉了,从而达到了我的目的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android
相关文章推荐