我只需要将itemDecoration添加到一个项目中。它起作用,但首先显示装饰没有自己的空间。但是当我开始滚动时,它将获得自己的空间。以下是我从here
部分获取的代码View spacer;
public NewMessageHeaderDecoration() {
spacer = null;
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
if (spacer == null) { // If layout is not already inflated
spacer = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_holder_new_messages_header, parent, false);
fixLayoutSize(spacer, parent);
}
// go through all the recycler views parents
for (int i = 0; i < parent.getChildCount(); i++) {
View child = parent.getChildAt(i);
int pos = parent.getChildAdapterPosition(child);
long msgSerial = ((ChatAdapter)parent.getAdapter()).getItemSerial(pos);
if(msgSerial == 40) {
c.save();
c.translate(0, child.getTop() - 2 - spacer.getHeight());
spacer.draw(c);
c.restore();
}
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
int position = parent.getChildAdapterPosition(view);
if (position == RecyclerView.NO_POSITION || position == 0 || spacer == null) {
return;
}
outRect.top = 2 + spacer.getHeight();
}
protected void fixLayoutSize(View view, ViewGroup parent) {
if (view.getLayoutParams() == null) {
view.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getWidth(), View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(parent.getHeight(), View.MeasureSpec.UNSPECIFIED);
int childWidth = ViewGroup.getChildMeasureSpec(widthSpec,
parent.getPaddingLeft() + parent.getPaddingRight(), view.getLayoutParams().width);
int childHeight = ViewGroup.getChildMeasureSpec(heightSpec,
parent.getPaddingTop() + parent.getPaddingBottom(), view.getLayoutParams().height);
view.measure(childWidth, childHeight);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
}