Skip to content

Instantly share code, notes, and snippets.

@mengdd
Created June 29, 2017 07:54
Show Gist options
  • Save mengdd/88211c8e78847cd6333cbc624ed608c0 to your computer and use it in GitHub Desktop.
Save mengdd/88211c8e78847cd6333cbc624ed608c0 to your computer and use it in GitHub Desktop.
ItemDecoration for RecyclerView, use View as Header
public class RecyclerHeadersDecoration extends RecyclerView.ItemDecoration {
private HeaderAdapter adapter;
private SparseArray<View> headers;
public interface HeaderAdapter {
boolean hasHeader(int position);
View getHeaderView(int position);
}
public RecyclerHeadersDecoration(HeaderAdapter adapter) {
this.adapter = adapter;
this.headers = new SparseArray<>();
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildLayoutPosition(view);
if (position != RecyclerView.NO_POSITION && adapter.hasHeader(position)) {
View headerView = adapter.getHeaderView(position);
headers.put(position, headerView);
measureHeaderView(headerView, parent);
outRect.top = headerView.getHeight();
} else {
headers.remove(position);
}
}
@Override
public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
for (int i = 0; i < parent.getChildCount(); i++) {
View child = parent.getChildAt(i);
int position = parent.getChildAdapterPosition(child);
if (position != RecyclerView.NO_POSITION && adapter.hasHeader(position)) {
canvas.save();
View headerView = headers.get(position);
canvas.translate(0, child.getY() - headerView.getHeight());
headerView.draw(canvas);
canvas.restore();
}
}
}
protected void measureHeaderView(View view, ViewGroup parent) {
if (view.getLayoutParams() == null) {
view.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
final DisplayMetrics displayMetrics = parent.getContext().getResources().getDisplayMetrics();
int widthSpec = View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, View.MeasureSpec.EXACTLY);
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());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment