給RecyclerView添加分割線

兩種方案:

1.在子布局文件中在相應的位置添加一條分割線。

2.使用RecyclerView提供的addItemDecoration方法設置自己定義的分割線。

? ? 使用自己定義的分割線其實是android已經提供了ItemDecoration這個類,供我們去復寫。

? ? 定義自己的分割線,有兩步:1.繪制分割線 2.設置分割線

? ? 對應了ItemDecoration中的兩個方法:onDraw(),getItemOffsets();

? ? 在onDraw()方法中我們繪制對應的分割線,主要根據布局方向來繪制

/**

* 繪制縱向的橫線

*

*@paramcanvas

*@paramparent

*/

private voiddrawVertical(Canvas canvas, RecyclerView parent) {

? ? ? final intleft = parent.getPaddingLeft();

? ? ? final intright = parent.getMeasuredWidth() - parent.getPaddingRight();

? ? ? final intchildSize = parent.getChildCount();

? ? ? for(inti =0; i < childSize; i++) {

? ? ? ? ? ? finalView child = parent.getChildAt(i);

? ? ? ? ? ? RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

? ? ? ? ? ? final inttop = child.getBottom();

? ? ? ? ? ? final intbottom = top +mItemSize;

? ? ? ? ? ? canvas.drawRect(left, top, right, bottom,paint);

? ? ? ?}

}

/**

* 繪制橫向的分割線

*

*@paramcanvas

*@paramparent

*/

private voiddrawHorizatal(Canvas canvas, RecyclerView parent) {

? ? ? ? ? ? final inttop = parent.getPaddingTop();

? ? ? ? ? ? final intbottom = parent.getMeasuredHeight() - parent.getPaddingBottom();

? ? ? ? ? ? final intchildSize = parent.getChildCount();

? ? ? ? ? ? for(inti =0; i < childSize; i++) {

? ? ? ? ? ? ? ? ? ? finalView child = parent.getChildAt(i);

? ? ? ? ? ? ? ? ? ? final intleft = child.getRight();

? ? ? ? ? ? ? ? ? ? final intright = left +mItemSize;

? ? ? ? ? ? ? ? ? ? canvas.drawRect(left, top, right, bottom,paint);

? ? ? ? ? ? }

}


在getItemOffsets()方法中我們設置分割線的

if(mOrientation== LinearLayout.HORIZONTAL) {

? ? ? ? ?outRect.set(0,0,0,mItemSize);

}else{

? ? ? ? ? outRect.set(0,0,mItemSize,0);

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容