我正在实现粘性标头项目装饰,但是我试图使标头覆盖该项目。我将代码基于timehop的库中。
https://github.com/timehop/sticky-headers-recyclerview
通过它的设计方式,项目装饰仍将创建一行,但是我希望它在实际列表中的高度为0。
这是当前粘性项目装饰的代码,该装饰需要创建自己的行。更改它使用的Rect
可以解决很多问题,但是我无法获得正确的结果。
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val itemPosition = parent.getChildAdapterPosition(view)
if (itemPosition == RecyclerView.NO_POSITION) {
return
}
if (mHeaderPositionCalculator.hasNewHeader(itemPosition, mOrientationProvider.isReverseLayout(parent))) {
val header = getHeaderView(parent, itemPosition)
setItemOffsetsForHeader(outRect, header, mOrientationProvider.getOrientation(parent))
}
}
/**
* Sets the offsets for the first item in a section to make room for the header view
*
* @param itemOffsets rectangle to define offsets for the item
* @param header view used to calculate offset for the item
* @param orientation used to calculate offset for the item
*/
private fun setItemOffsetsForHeader(itemOffsets: Rect, header: View, orientation: Int) {
mDimensionCalculator.initMargins(mTempRect, header)
// should I modify itemOffsets here?
if (orientation == LinearLayoutManager.VERTICAL) {
itemOffsets.top =header.height + mTempRect.top + mTempRect.bottom
} else {
itemOffsets.left = header.width + mTempRect.left + mTempRect.right
}
}
override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDrawOver(canvas, parent, state)
val childCount = parent.childCount
if (childCount <= 0 || mAdapter.itemCount <= 0) {
return
}
for (i in 0 until childCount) {
val itemView = parent.getChildAt(i)
val position = parent.getChildAdapterPosition(itemView)
if (position == RecyclerView.NO_POSITION) {
continue
}
val hasStickyHeader = mHeaderPositionCalculator.hasStickyHeader(itemView, mOrientationProvider.getOrientation(parent), position)
if (hasStickyHeader || mHeaderPositionCalculator.hasNewHeader(position, mOrientationProvider.isReverseLayout(parent))) {
val header = mHeaderProvider.getHeader(parent, position)
//re-use existing Rect, if any.
var headerOffset: Rect? = mHeaderRects.get(position)
if (headerOffset == null) {
headerOffset = Rect()
mHeaderRects.put(position, headerOffset)
}
mHeaderPositionCalculator.initHeaderBounds(headerOffset, parent, header, itemView, hasStickyHeader)
// should I modify headerOffset here?
mRenderer.drawHeader(parent, canvas, header, headerOffset)
}
}
}