RecyclerView 自定义item间隔

本文介绍了如何在Android的RecyclerView中实现自定义item间隔,通过继承RecyclerView.ItemDecoration进行设置。同时,文章强调了根据不同item位置设置间隔的可能性。在获取item位置时,需要注意getChildLayoutPosition可能因动画未完成返回旧位置的问题,特别是在执行notifyItemInsert()后立即调用该方法时。

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

RecyclerView 自定义item间隔

通过继承RecyclerView.ItemDecoration实现自定义item间隔

recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.set(left,top,right,bottom);
    }
});

我们也可以根据item的不同位置设置不同的间隔

recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
         if (parent.getChildAdapterPosition(view) == positon) {
             outRect.set(left,top,right,bottom);
         }
    }
});

获取位置有两个方法

/**
  * Return the adapter position that the given child view corresponds to.
  *
  * @param child Child View to query
  * @return Adapter position corresponding to the given view or {@link #NO_POSITION}
  */
public int getChildAdapterPosition(View child) {
        final ViewHolder holder = getChildViewHolderInt(child);
        return holder != null ? holder.getAdapterPosition() : NO_POSITION;
}

/**
  * Return the adapter position of the given child view as of the latest completed layout pass.
  * <p>
  * This position may not be equal to Item's adapter position if there are pending changes
  * in the adapter which have not been reflected to the layout yet.
  *
  * @param child Child View to query
  * @return Adapter position of the given View as of last layout pass or {@link #NO_POSITION} if
  * the View is representing a removed item.
  */
public int getChildLayoutPosition(View child) {
    final ViewHolder holder = getChildViewHolderInt(child);
    return holder != null ? holder.getLayoutPosition() : NO_POSITION;
}

简单说就是getChildLayoutPosition方法可能会由于RecyclerView的动画未执行完毕,而返回了旧的位置,比如说执行了notifyItemInsert()后立即执行getChildLayoutPosition就会返回未添加item之前的位置,使用时需要注意。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值