自定义 View 结合 RecyclerView 实现时光轴效果
时光轴效果在很多 App 中都有出现,例如淘宝中的快递跟踪、用户成长记录等。本文将使用 RecyclerView 配合自定义 View 来实现时光轴效果。
1. 自定义属性
首先,我们需要在 res/values/attrs.xml 中声明自定义属性,以便在 XML 布局中配置时光轴的样式。
<declare-styleable name="TimeLine">
<attr name="beginLine" format="reference" />
<attr name="endLine" format="reference" />
<attr name="lineWidth" format="dimension" />
<attr name="timeLineImage" format="reference" />
<attr name="timeLineImageSize" format="dimension" />
</declare-styleable>
各属性说明:
beginLine: 上方线条的 Drawable 资源。endLine: 下方线条的 Drawable 资源。lineWidth: 线条的宽度。timeLineImage: 中间圆形节点的 Drawable 资源。timeLineImageSize: 中间圆形节点的大小(宽高一致)。
2. 自定义 TimeLine 控件
创建一个继承自 View 的类 TimeLine。在构造方法中解析自定义属性。
public class {
lineWidth;
Drawable mBeginLine;
Drawable mEndLine;
Drawable mTimeLineImage;
mTimeLineImageSize;
{
(context, );
}
{
(context, attrs, );
}
{
(context, attrs, defStyleAttr);
context.obtainStyledAttributes(attrs, R.styleable.TimeLine);
lineWidth = a.getDimensionPixelOffset(R.styleable.TimeLine_lineWidth, );
mBeginLine = a.getDrawable(R.styleable.TimeLine_beginLine);
mEndLine = a.getDrawable(R.styleable.TimeLine_endLine);
mTimeLineImage = a.getDrawable(R.styleable.TimeLine_timeLineImage);
mTimeLineImageSize = a.getDimensionPixelSize(R.styleable.TimeLine_timeLineImageSize, );
a.recycle();
}
}


