Android Recyclerview设置Item之间的间距

本文介绍了如何在RecyclerView中为每个item添加底部内边距,特别是解决最后一项缺失下边距的问题。通过在item布局文件中设置根布局的paddingBottom,然后在RecyclerView中设置clipToPadding为false并添加paddingBottom,可以确保所有item包括最后一项都有8dp的下边距。这种方法避免了自定义LayoutParams和ItemDecoration的复杂性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

其实不需要自定义LinearLayout.LayoutParams 跟RecyclerView.ItemDecoration。
假设:要在recycleView的每条item的下加一个8dp的边距:
第一步:
在每个item的布局的根布局加上paddingBottom。

<?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="wrap_content"
    android:paddingBottom="9dp">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="13dp"
            android:textColor="#ff5e5c5c"
            android:textSize="9sp"/>
    </RelativeLayout>

</RelativeLayout>

此时前面的所以item都有8dp的下边距,但是最后一条item没有下边距;

第二步:
在RecycleView里设置属性clipToPadding、paddingBottom就可以了

<androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recy_alert_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="false"
            android:paddingBottom="8dp"/>

此处的paddingBottom由于受到clipToPadding属性的影响并不会作用到所有的子item中,设置完以后,你就会看到,最后一条item也有了8dp的底部内边距。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值