先上效果图,DEMO在最下面
这个控件其实算是比较轻量级的,相信不少小伙伴都能做出来。因为项目中遇到了一些特殊的定制要求,所以就自己写了一个,这里放出来。
首先来分析下这个控件的功能:
- 能够响应左右滑动,并且能响应快速滑动
- 选择项和未选择项有不同的样式表现,比如前景色,背景色,字体大小变粗之内的
- 在切换选项的时候,如果当前选项未完全呈现在界面前,则自动滚动直至当前选项完全暴露显示
前两条还有,简简单单就实现了,主要是第三点,这才是我自定义这个控件的原因!那么如果要实现这个控件,需要用到哪些知识呢?
- 用Scroller来实现控件的滚动
- 用VelocityTracker来实现控件的快速滚动
如果上面两种技术你都已经会了,那么我们就可以开始讲解代码了。首先是一些属性的Getter/Setter方法,这里采用的链式设置法:
public IndicatorView color(int colorDefault, int colorSelected, int colorBg){
this.colorDefault = colorDefault;
this.colorSelected = colorSelected;
this.colorBg = colorBg;
return this;
}
public IndicatorView textSize(int textSize){
this.textSize = textSize;
return this;
}
public IndicatorView text(String[] texts){
this.texts = texts;
return this;
}
public IndicatorView padding(int[] padding){
this.padding = padding;
return this;
}
public IndicatorView defaultSelect(int defaultSelect){
this.selectItem = defaultSelect;
return this;
}
public IndicatorView lineHeight(int lineHeight){
this.lineHeight = lineHeight;
return this;
}
public IndicatorView listener(OnIndicatorChangedListener listener){
this.listener = listener;
return this;
}
public IndicatorView type(Type type){
this.type = type;
return this;
}
public class Item {
String text;
int colorDefault;
int colorSelected;
int textSize;
boolean isSelected = false;
int width;
Point drawPoint;
int[] padding = new int[4];
Rect rect = new Rect();
}
然后是控件的初始化操作,主要根据当前控件的宽高,以及设置的一些属性,进行Item选项的初始化:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
width = MeasureSpec.getS