RecyclerView 自定义item间隔

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之前的位置,使用时需要注意。

阅读更多
文章标签: android
个人分类: android
上一篇718. Maximum Length of Repeated Subarray
下一篇Android 两种轮询的简单写法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭