由于项目需求,个人信息的输入是以一个刻度尺滑动作为数据选择方法输入。如下图
哎呦喂,貌似看起来很简单的样子,但又好像不知从拿入手实现。实话说,确实不好做,所以~~~百度~~~哈哈哈哈。
然而,结果令我有点失望,网上的解决办法并不多,现成的工程又不符合自己的需求,改起来又耗时间,那咋办呢?
一个点子瞬间闪亮,没错,一条很长的图片加HorizontalSrcollView,重写onScrollChange(),用接口将其滑动距离暴露出来。。。。总之,可以实现。嗯,小满足~
然后,你就真的满足了?反正我可不满意。因为个人感觉太依赖图片的程序猿要不就是大牛,写多了懒得写了,直接上图;要不就是不会菜鸟,不会嘛~
所以,我在项目即将完结之前,升级了下装备,绕回来把这最终Boss解决了。
废话少说,转入正题:
首先,先上个效果图:
第一步,定义好view的属性,创建attrs属性:
attrs.xml
<declare-styleable name="Ruler">
<attr name="interval" format="dimension"/>
<attr name="fromValue" format="integer"/>
<attr name="toValue" format="integer"/>
<attr name="currentValue" format="integer"/>
<attr name="intervalsBetweenValues" format="integer"/>
<attr name="valuesInterval" format="integer"/>
<attr name="valuesTextSize" format="dimension"/>
<attr name="valuesTextColor" format="color"/>
<attr name="linesWidth" format="dimension"/>
<attr name="linesColor" format="color"/>
<attr name="isShowPointer" format="boolean"/>
<attr name="orientation">
<enum name="vertical" value="0"/>
<enum name="horizontal" value="1"/>
</attr>
</declare-styleable>
上面的属性都在代码里有注释:
//间隔,即两条刻度之间的距离
private int interval;
//起始值
private int fromValue;
//结束值
private int toValue;
//每两个值之间的间隔数,也指多少个最小单位,比如0cm到1cm有10个最小单位1mm
private int intervalsBetweenValues;
//相邻两个值的跳跃间隔,如上面第一张图的10000到11000,中间的跳跃值就是1000
private int valuesInterval;
//当前值
private int currentValue;
//值的文本大小
private int valuesTextSize;
//值的文本颜色
private int valuesTextColor;
//刻度的宽度
private int linesWidth;
//刻度的颜色
private int linesColor;
//刻度尺是vertical还是horizontal,上面第一张图的就是horizontal
private int orientation;
第二步,构造体内利用TypedArray收集其属性,以及画笔,一些其他变量的初始化。
interval=array.getDimensionPixelSize(R.styleable.Ruler_interval, dp2px(intervalsBetweenValues));
fromValue=array.getInt(R.styleable.Ruler_fromValue, 0);
toValue=array.getInt(R.styleable.Ruler_toValue, intervalsBetweenValues);
currentValue=array.getInt(R.styleable.Ruler_currentValue, (fromValue+toValue)/2);
intervalsBetweenValues=array.getInt(R.styleable.Ruler_intervalsBetweenValues, intervalsBetweenValues);
valuesInterval=array.getInt(R.styleable.Ruler_valuesInterval, 1);
valuesTextSize=array.getDimensionPixelSize(R.styleable.Ruler_valuesTextSize, sp2px(16));
valuesTextColor=array.getColor(R.styleable.Ruler_valuesTextColor, Color.BLACK);
linesWidth=array.getDimensionPixelSize(R.styleable.Ruler_linesWidth, dp2px(1));
linesColor=array.getColor(R.styleable.Ruler_linesColor, Color.BLACK);
orientation=array.getInt(R.styleable.Ruler_orientation, HORIZONTAL);
第三步,不需要重写onMeasure,定义布局时应固定长宽,直接重写onDraw,先画好一帧画面,后面的重绘就根据这一帧画,这里才是关键。
这里只以垂直的刻度尺为例:
if(orientation==VERTICAL){
//画中间的指针,就在中间画,很简单