最近想做一个通讯录的项目玩玩,因为受够了一加手机自带的版本。想着在上面加一个自动循环播放的文本组件,说起这个,可能很多人都会想起TextView自带的跑马灯效果配置。开始也试着用了一下,不过后来感觉局限性确实太大,就放弃了;这里发放一个自定义的循环播放的组件。
跑马灯配置局限:
1、 不同版本的配置可能不同
2、 必须文本超出文本框的大小
3、 必须在获取焦点的时候才能循环
4、就算设置一直获取焦点,但是在和EditText, ListView这种组件同时存在时,还是会默认不获取焦点
这里的循环播放组件也是继承TextView, TextView的属性可以完全使用,而且可以设置播放速度以及播放的方向,正在使用没有BUG。。。
我这里是继承的TraceTextView, 这个只是为了统一设置字体一个TextView子类,完全可以直接继承自TextView,然后把setFont方法去掉即可
public class MarqueeTextView extends TraceTextView { private Paint paint; /*文本的长度*/ private int textWidth; /*滚动速度*/ private int speedScrolling = 1; /*是否正在滚动*/ private boolean scrolling = false; /*文本起始位置*/ private int left; /*Y方向的偏移量*/ private static final int OFFSET_Y = 8; /*滚动方向: 1->向左滚动,2->向右滚动*/ private int scrollDirection = 1; public MarqueeTextView(Context context) { super(context); init(); } public MarqueeTextView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { initPaint(); } private void initPaint() { paint = new Paint(); paint.setTextSize(getTextSize()); paint.setColor(getCurrentTextColor()); paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); } @Override protected void onDraw(Canvas canvas) { textWidth = ViewUtils.measureTextLength(getText().toString(), paint); final float top = getMeasuredHeight() / 2 + (paint.descent() - paint.ascent()) / 2 - 10; if (!scrolling) { if (textWidth >= (getMeasuredWidth() - getPaddingLeft() - getPaddingRight())) { left = 0; } else { left = (getMeasuredWidth() - textWidth) / 2 + getPaddingLeft(); } scrolling = true; } else { onDirection(); } onRange(); canvas.drawText(getText().toString(), left, top, paint); invalidate(); } /** * 方向判定 */ private void onDirection() { if (scrollDirection == 1) { // 向左滚动 left -= speedScrolling; } if (scrollDirection == 2) { // 向右滚动 left += speedScrolling; } } /** * 边界判定 */ private void onRange() { if (scrollDirection == 1) { // 左边界判定 if (left <= -textWidth) { left = getMeasuredWidth() + textWidth - getPaddingRight(); } } if (scrollDirection == 2) { // 右边界判定 if (left > getMeasuredWidth() - getPaddingRight()) { left = -(getMeasuredWidth() - getPaddingLeft()); } } } @Override public void setFont(int position) { super.setFont(position); FontHelper.setFont(getContext(), position, paint); } @Override public void setTextColor(int color) { super.setTextColor(color); paint.setColor(color); } @Override public void setTextSize(float size) { super.setTextSize(size); paint.setTextSize(size); } /** * 设置滚动速度 * * @param speed */ public void setScrollSpeed(int speed) { speedScrolling = speed; } /** * 设置滚动方向 * * @param direction */ public void setDirection(int direction) { scrollDirection = direction; } }
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦