Android中使用itemdecoration实现时间线效果
代码如下:
// 时间线装饰器 public class TimeLineDecoration extends RecyclerView.ItemDecoration { private Paint mPaint; public TimeLineDecoration() { mPaint = new Paint(); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(Color.BLUE); mPaint.setStrokeWidth(5); } @Override public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { super.onDraw(c, parent, state); RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); // 这里的childcount为可见item的个数。 与item的个数不一定相同。 int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { View child = parent.getChildAt(i); // 避免硬编码,这里通过代码获取在getItemOffsets方法中设置的宽度 int leftDecoWidth = layoutManager.getLeftDecorationWidth(child); // 根据position获取当前的数据,然后根据数据状态绘制不同的形状 int position = parent.getChildAdapterPosition(child); int cx = leftDecoWidth / 2; int cy = child.getTop() + child.getHeight() / 2; int radius = 20; if (position == 2) { c.drawRect(cx - radius, cy - radius, cx + radius, cy + radius, mPaint); } else if (position == 4) { // 绘制外圈为空心圆,内圈为实心圆 mPaint.setStyle(Paint.Style.STROKE); c.drawCircle(cx, cy, radius, mPaint); mPaint.setStyle(Paint.Style.FILL); c.drawCircle(cx, cy, radius >> 1, mPaint); } else { c.drawCircle(cx, cy, radius, mPaint); } // 绘制item中间的连接线,第一个item与最后一个item的连接线需单独处理一下。 if (position == 0) { c.drawLine(cx, cy + mPaint.getStrokeWidth() + radius, cx, child.getBottom(), mPaint); } else if (position == parent.getAdapter().getItemCount() - 1) { c.drawLine(cx, child.getTop(), cx, cy - mPaint.getStrokeWidth() - radius, mPaint); } else { c.drawLine(cx, cy + mPaint.getStrokeWidth() + radius, cx, child.getBottom(), mPaint); c.drawLine(cx, child.getTop(), cx, cy - mPaint.getStrokeWidth() - radius, mPaint); } } } @Override public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { super.onDrawOver(c, parent, state); // 不受outRect设置的范围影响,可以绘制在item上。 } @Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); // 在item左边留下100像素的空间。 item的布局会在减掉这100像素后处理。 outRect.left = 100; } }
然后将该itemdecoration设置到recyclerview上。
RecyclerAdapter adapter = new RecyclerAdapter(this, data); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.addItemDecoration(new TimeLineDecoration()); mRecyclerView.setAdapter(adapter);
实现效果如下:
之前在其他地方学习到,还可以通过在item layout中实现时间线的效果。
参考:
1、启舰博客。
到此这篇关于Android中使用itemdecoration实现时间线效果的文章就介绍到这了,更多相关itemdecoration实现时间线内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)