Last active
November 14, 2019 00:00
-
-
Save rockerhieu/1206077511ed7f3aa4dace139a66d203 to your computer and use it in GitHub Desktop.
This file contains 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
import android.graphics.Canvas; | |
import android.graphics.Rect; | |
import android.view.View; | |
import androidx.annotation.NonNull; | |
import androidx.recyclerview.widget.RecyclerView; | |
public class HeaderItemDecoration extends RecyclerView.ItemDecoration { | |
private View headerView; | |
public HeaderItemDecoration(View headerView) { | |
this.headerView = headerView; | |
} | |
@Override public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, | |
@NonNull RecyclerView.State state) { | |
super.onDraw(c, parent, state); | |
headerView.layout(parent.getLeft(), 0, parent.getRight(), headerView.getMeasuredHeight()); | |
for (int i = 0; i < parent.getChildCount(); i++) { | |
View view = parent.getChildAt(i); | |
if (parent.getChildAdapterPosition(view) == 0) { | |
c.save(); | |
int height = headerView.getMeasuredHeight(); | |
int top = view.getTop() - height; | |
c.translate(0f, top); | |
headerView.draw(c); | |
c.restore(); | |
break; | |
} | |
} | |
} | |
@Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, | |
@NonNull RecyclerView parent, @NonNull RecyclerView.State state) { | |
if (parent.getChildAdapterPosition(view) == 0) { | |
headerView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), | |
View.MeasureSpec.AT_MOST), | |
View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), | |
View.MeasureSpec.AT_MOST)); | |
outRect.set(0, headerView.getMeasuredHeight(), 0, 0); | |
} else { | |
super.getItemOffsets(outRect, view, parent, state); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment