android浮动广告代码,Android自定义View实现仿1号店垂直滚动广告条代码

效果图展示,图片有点卡,耐心看会,原程序是很流畅的

73764e1b2227a195bde239dd654ede27.gif

实现步骤:

声明变量

初始化画笔、文本大小和坐标

onMeasure()适配wrap_content的宽高

onDraw()画出根据坐标画出两段Text

监听点击事件

在Activity中实现点击事件

实现原理(坐标变换原理):整个过程都是基于坐标Y的增加和交换进行处理的,Y值都会一直增加到endY,然后进行交换逻辑

9a188d0be387d350f26cb7a46473f6e1.png

步骤一:声明变量

由于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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值