RecyclerView custom item interval
Implement custom item interval by inheriting RecyclerView.ItemDecoration
recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.set(left,top,right,bottom);
}
});
We can also set different intervals according to different positions of item s
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);
}
}
});
There are two ways to get a location
/**
* 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;
}
In short, the getChildLayoutPosition method may return to the old position due to the unfinished animation of RecyclerView. For example, if you execute notifyItemInsert() and execute getChildLayoutPosition immediately, it will return to the position before the item was added. You need to pay attention when using it.