效果图展示,图片有点卡,耐心看会,原程序是很流畅的
实现步骤:
声明变量
初始化画笔、文本大小和坐标
onMeasure()适配wrap_content的宽高
onDraw()画出根据坐标画出两段Text
监听点击事件
在Activity中实现点击事件
实现原理(坐标变换原理):整个过程都是基于坐标Y的增加和交换进行处理的,Y值都会一直增加到endY,然后进行交换逻辑
步骤一:声明变量
由于1号店是两句话的滚动,所以我们也是使用两句话来实现的
private Paint mPaint;
private float x, startY, endY, firstY, nextStartY, secondY;
//整个View的宽高是以第一个为标准的,所以第二句话长度必须小于第一句话
private String[] text = {"今日特卖:毛衣3.3折>>>", "公告:全场半价>>>"};
private float textWidth, textHeight;
//滚动速度
private float speech = 0;
private static final int CHANGE_SPEECH = 0x01;
//是否已经在滚动
private boolean isScroll = false;
步骤二:初始化画笔、文本大小和坐标
以第一句话为标准来做控件的宽高标准
//初始化画笔
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setTextSize(30);
//测量文字的宽高,以第一句话为标准
Rect rect = new Rect();
mPaint.getTextBounds(text[0], 0, text[0].length(), rect);
textWidth = rect.width();
textHeight = rect.height();
//文字开始的x,y坐标
//由于文字是以基准线为基线的,文字底部会突出一点,所以向上收5px
x = getX() + getPaddingLeft();
startY = getTop() + textHeight + getPaddingTop() - 5;
//文字结束的x,y坐标
endY = startY + textHeight + getPaddingBottom();
//下一个文字滚动开始的y坐标
//由于文字是以基准线为基线的,文字底部会突出一点,所以向上收5px
nextStartY = getTop() - 5;
//记录开始的坐标
firstY = startY;
secondY = nextStartY;
步骤三:onMeasure()适配wrap_content的宽高
如果学习过自定义View的话,下面的代码应该很熟悉,就是适配warp_content的模板代码:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec);
setMeasuredDimension(width, height);
}
private int measureHeight(int heightMeasureSpec) {
int result = 0;
int size = MeasureSpec.getSize(heightMeasureSpec);
int mode = MeasureSpec.getMode(heightMeasureSpec);
if (mode == MeasureSpec.EXACTLY) {
result = size;
} else {
result = (int) (getPaddingTop() + getPaddingBottom() + textHeight);
if (mode == MeasureSpec.AT_MOST) {
result = Math.min(result, size);
}
}
return result;
}
private int measureWidth(int widthMeasureSpec) {
int result = 0;
int size = MeasureSpec.getSize(widthMeasureSpec);
int mode = MeasureSpec.getMode(widthMeasureSpec);
if (mode == MeasureSpec.EXACTLY) {
result = size;
} else {
result = (int) (getPaddingLeft() + getPaddingRight() + textWidth);
if (mode == MeasureSpec.AT_MOST) {
result = Math.min(result, size);
}
}
return result;
}