Last active
July 1, 2018 04:39
-
-
Save li2/a406fe05e624fd5860793128b14b5668 to your computer and use it in GitHub Desktop.
RecyclerView divider ItemDecoration recyclerView.addItemDecoration( new TelsieDividerItemDecoration(ContextCompat.getDrawable(getContext(), R.drawable.telsie_divider), 32, 16)); #tags: android-list
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 TelsieDividerItemDecoration extends RecyclerView.ItemDecoration { | |
| private Drawable mDivider; | |
| private int mLeftMargin; | |
| private int mRightMargin; | |
| /** | |
| * | |
| * @param divider | |
| * @param left left margin of the divider, unit DP | |
| * @param right right margin of the divider, unit DP | |
| */ | |
| public TelsieDividerItemDecoration(Drawable divider, int left, int right) { | |
| mDivider = divider; | |
| mLeftMargin = left; | |
| mRightMargin = right; | |
| } | |
| @Override | |
| public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { | |
| super.getItemOffsets(outRect, view, parent, state); | |
| if (parent.getChildAdapterPosition(view) == 0) { | |
| return; | |
| } | |
| outRect.top = mDivider.getIntrinsicHeight(); | |
| } | |
| @Override | |
| public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) { | |
| int dividerLeft = parent.getPaddingLeft() + (int) ViewUtils.getPixelValueFromDIP(parent.getContext(), mLeftMargin); | |
| int dividerRight = parent.getWidth() - parent.getPaddingRight() - (int) ViewUtils.getPixelValueFromDIP(parent.getContext(), mRightMargin); | |
| int childCount = parent.getChildCount(); | |
| for (int i = 0; i < childCount - 1; i++) { | |
| View child = parent.getChildAt(i); | |
| RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); | |
| int dividerTop = child.getBottom() + params.bottomMargin; | |
| int dividerBottom = dividerTop + mDivider.getIntrinsicHeight(); | |
| mDivider.setBounds(dividerLeft, dividerTop, dividerRight, dividerBottom); | |
| mDivider.draw(canvas); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment