本文主要是介绍实现 Recyclerview 的分割线 RecyclerDecoration,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/*** RecyclerView 的分割线** Created by suwenlai on 16-12-27.*/public class RecyclerDecoration extends RecyclerView.ItemDecoration {private static final int[] ATTRS = new int[]{android.R.attr.listDivider};private Drawable mDivider;private Context mContext;private int mOrientation;public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;public RecyclerDecoration(Context context, int orientation) {mContext = context;TypedArray typedArray = context.obtainStyledAttributes(ATTRS);mDivider = typedArray.getDrawable(0);typedArray.recycle();setOrientation(orientation);}/*** 设置布局方向** @param orientation*/public void setOrientation(int orientation) {if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST){throw new IllegalArgumentException("invalid orientation");}mOrientation = orientation;}@Overridepublic void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {if (mOrientation == HORIZONTAL_LIST) {drawVerticalLine(c, parent, state);} else {drawHorizontalLine(c, parent, state);}}/*** 画竖线** @param c* @param parent* @param state*/private void drawVerticalLine(Canvas c, RecyclerView parent, RecyclerView.State state) {int top = parent.getPaddingTop();int bottom = parent.getHeight() - parent.getPaddingBottom();int childCount = parent.getChildCount();for (int i = 0; i < childCount; i++) {View child = parent.getChildAt(i);RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();int left = child.getRight() + params.rightMargin;int right = left + mDivider.getIntrinsicWidth();mDivider.setBounds(left, top, right, bottom);mDivider.draw(c);}}/*** 画横线** @param c* @param parent* @param state*/private void drawHorizontalLine(Canvas c, RecyclerView parent, RecyclerView.State state) {int left = parent.getPaddingLeft();int right = parent.getWidth() - parent.getPaddingRight();int childCount = parent.getChildCount();for (int i = 0; i < childCount; i++) {View child = parent.getChildAt(i);RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();int top = child.getBottom() + params.bottomMargin;int bottom = top + mDivider.getIntrinsicHeight();mDivider.setBounds(left, top, right, bottom);mDivider.draw(c);}}@Overridepublic void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {if (mOrientation == HORIZONTAL_LIST) {outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);} else {outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());}}
}
这篇关于实现 Recyclerview 的分割线 RecyclerDecoration的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!