滚动的TextView

public class ScrollTextView extends TextView implements View.OnClickListener {

	private final String TAG = ScrollTextView.class.getSimpleName();
	private float textLength;//文本长度
	private float viewWidth;
	private float step;//文字的横坐标
	private float y;//文字的纵坐标
	public boolean isStarting = true;//是否开始滚动
	private Paint paint; //绘图样式
	private String text = "";//文本内容
	private int marqueeRepeatLimit = 3;
	private int currentRepeatLimit;

	public ScrollTextView(Context context) {
		super(context);
		init();
	}

	public ScrollTextView(Context context, @Nullable AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {
		paint = getPaint();
		paint.setColor(getCurrentTextColor());
		text = getText().toString();
		textLength = paint.measureText(text);
		y = getTextSize() + 5;
		this.setOnClickListener(this);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		if (textLength <= viewWidth){
			isStarting = false;
			super.onDraw(canvas);
			return;
		}
		canvas.drawText(text, - step, y, paint);
		if(!isStarting) return;
		step += 1;//为文字滚动速度。
		if(step >= textLength) {
			step = -viewWidth;
			currentRepeatLimit++;
			DL.d(TAG, "onDraw: currentRepeatLimit=" + currentRepeatLimit);
			if (currentRepeatLimit == marqueeRepeatLimit){
				step = 0;
				isStarting = false;
			}
		}
		invalidate();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		if (viewWidth != View.MeasureSpec.getSize(widthMeasureSpec)){
			viewWidth = View.MeasureSpec.getSize(widthMeasureSpec);
		}
		float width = getPaint().measureText(this.text);
		if (width != textLength){
			textLength = width;
			if (!isStarting){
				currentRepeatLimit = 0;
				isStarting = true;
				invalidate();
			}
		}
	}

	@Override
	public void setText(CharSequence text, TextView.BufferType type) {
		super.setText(text, type);
		if (text != null) {
			this.text = text.toString();
		}
		step = 0;
		isStarting = true;
		currentRepeatLimit = 0;
	}

	@Override
	public void onClick(View v) {
		if (textLength <= viewWidth){
			return;
		}
		if (!isStarting){
			currentRepeatLimit = 0;
			isStarting = true;
			invalidate();
		}
	}

	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus) {
		super.onWindowFocusChanged(hasWindowFocus);
		DL.d(TAG, "onWindowFocusChanged: hasWindowFocus=" + hasWindowFocus);
		if (!hasWindowFocus){
			step = 0;
			isStarting = false;
		}
	}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值