滾動的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;
		}
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章