Created
June 29, 2017 07:54
-
-
Save mengdd/88211c8e78847cd6333cbc624ed608c0 to your computer and use it in GitHub Desktop.
ItemDecoration for RecyclerView, use View as Header
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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