今天就跟大家聊聊有关如何在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);
看完上述内容,你们对如何在Android中利用itemdecoration实现一个时间线效果有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。