自定义的跑马灯控件

package com.home.view;

import com.home.util.DataUtil;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 自定义的跑马灯控件
 * 
 * @author fengjian
 * 
 */
public class MarqueeView extends TextView {

	/** 是否停止滚动 */
	private boolean mStop;
	private String mText;
	private float mCoordinateX;
	private float mTextWidth;

	public MarqueeView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public MarqueeView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public MarqueeView(Context context) {
		super(context);
	}

	/**
	 * 设置文本并启动跑马灯效果
	 * 
	 * @param text
	 *            文本内容
	 */
	public void setText(String text) {
		this.mText = text;
		mTextWidth = getPaint().measureText(mText);
		if (mHandler.hasMessages(0))
			mHandler.removeMessages(0);
		mHandler.sendEmptyMessageDelayed(0, 2000);
	}

	/**
	 * 停止跑马灯效果
	 */
	public void stop() {
		mStop = true;
	}

	@Override
	protected void onAttachedToWindow() {
		mStop = false;
		if (!DataUtil.isEmpty(mText))
			mHandler.sendEmptyMessageDelayed(0, 2000);
		super.onAttachedToWindow();
	}

	@Override
	protected void onDetachedFromWindow() {
		mStop = true;
		if (mHandler.hasMessages(0))
			mHandler.removeMessages(0);
		super.onDetachedFromWindow();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (!DataUtil.isEmpty(mText))
			canvas.drawText(mText, mCoordinateX, 15, getPaint());
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				if (Math.abs(mCoordinateX) > (mTextWidth + 100)) {
					mCoordinateX = 0;
					invalidate();
					if (!mStop) {
						sendEmptyMessageDelayed(0, 2000);
					}
				} else {
					mCoordinateX -= 1;
					invalidate();
					if (!mStop) {
						sendEmptyMessageDelayed(0, 30);
					}
				}

				break;
			}
			super.handleMessage(msg);
		}
	};

}

原文转自:农民伯伯: http://www.cnblogs.com/over140/p/3687952.html

你可能感兴趣的:(android,跑马灯)