前言
今天在網上看到一篇文章中有個時間軸圖片,很是符合我的審美,在能表現出要表達給用戶的信息外,極盡簡約,很漂亮,打算實現一下。好吧,文章https://www.jianshu.com/p/d03f994b6c44已經給出了實現方式,再copy一遍?No,換一種思路吧。
我的效果
1.只有1條發貨數據
2.多於2條數據
右邊的實現
右邊的實際就是一個普通的不能再普通的RecyclerView了,這裏不再贅述。
左邊的時間軸實現
mRecyclerView.addItemDecoration(new TimeLineItemDecoration());
原文中的效果是通過item實現的,我這裏換了一個思路,使用TimeLineItemDecoration來做的:
public class TimeLineItemDecoration extends RecyclerView.ItemDecoration {
private int mCircleSize = 14;//圓圈的半徑
private Paint mPaint;//畫筆
private int mPaintSize = 6;//畫筆寬度
private String mPaintColor = "#B8B8B8";//畫筆默認顏色
public TimeLineItemDecoration() {
mPaint = new Paint();
mPaint.setStrokeWidth(mPaintSize);
mPaint.setColor(Color.parseColor(mPaintColor));
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
Rect rect = new Rect(200, 0, 0, 0);//使item從outRect中右移200px
outRect.set(rect);
}
@Override
public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
super.onDraw(canvas, parent, state);
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
int left = child.getLeft();
int top = child.getTop();
int bottom = child.getBottom();
int right = child.getRight();
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int bottomMargin = params.bottomMargin;//防止在item根佈局中設置marginTop和marginBottom
int topMargin = params.topMargin;
int leftX = left / 2;//軸線的x軸座標
int height = child.getHeight();//item的高度,不包含Margin
if (childCount==1){
canvas.drawLine(leftX, top, leftX, bottom - height / 2, mPaint);
}else {
if (i == 0) {
canvas.drawLine(leftX, top + height / 2, leftX, bottom + bottomMargin, mPaint);
} else if (i == childCount - 1) {
canvas.drawLine(leftX, top - topMargin, leftX, bottom - height / 2, mPaint);
} else {
canvas.drawLine(leftX, top - topMargin, leftX, bottom - height / 2, mPaint);
canvas.drawLine(leftX, top + height / 2, leftX, bottom + bottomMargin, mPaint);
}
}
canvas.drawCircle(leftX, top + height / 2, mCircleSize, mPaint);
}
}
}
涉及文件
只用到了紅框中的文件,可以copy到自己的項目中試試。歡迎瀏覽提出issue。