自定义网格和瀑布流布局的分割线RecyclerView.ItemDecoration

public class DividerGridItemDecoration extends RecyclerView.ItemDecoration{
    private  final int[] ATTRS = new int[]{android.R.attr.listDivider};
    private Drawable drawable;
    public DividerGridItemDecoration(Context context){
        TypedArray typedArray = context.obtainStyledAttributes(ATTRS);
        drawable = typedArray.getDrawable(0);
        typedArray.recycle();
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        drawHorizontal(parent,c);
        drawVertical(parent,c);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
    }
    private void drawVertical(RecyclerView parent,Canvas canvas){
        int childCount = parent.getChildCount();
        for(int i=0;i= childCount){
                    return  true;
                }
            }
        }
        return false;
    }

    private boolean isLastRow(RecyclerView parent,int childCount,int position,int spanCount){
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if(layoutManager instanceof GridLayoutManager){
            if(position >= (childCount - childCount%spanCount)){
                return  true;
            }
        }else if(layoutManager instanceof StaggeredGridLayoutManager){
            if(((StaggeredGridLayoutManager) layoutManager).getOrientation() == StaggeredGridLayoutManager.VERTICAL){
                if(position >= (childCount - childCount%spanCount)){
                    return  true;
                }
            }else{
                if((position + 1)%spanCount == 0){
                    return true;
                }
            }
        }
        return false;
    }


    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int spanCount = getSpanCount(parent);
        int childCount = parent.getAdapter().getItemCount();
        int position = parent.getChildAdapterPosition(view);
        if(isLastColum(parent,spanCount,position,childCount)){
            outRect.set(0,0,0,drawable.getIntrinsicHeight());
        }else if(isLastRow(parent,childCount,position,spanCount)){
            outRect.set(0,0,drawable.getIntrinsicWidth(),0);
        }else{
            outRect.set(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
        }
    }
}

你可能感兴趣的:(android)