天天看点

Android文字跑马灯控件(文本自动滚动控件,左右移动 带源码)

                                  转载请注明地址:http://blog.csdn.net/u014608640/article/details/52486324

      最近在开发一个应用,需要用到文本的跑马灯效果,所以简单的处理了一下:

           首先:看一下效果图:

Android文字跑马灯控件(文本自动滚动控件,左右移动 带源码)
代码如下:

主页:

public class MainActivity extends Activity implements OnClickListener {

	private Button mBtnNext;
	private Button mBtnPrev;
	private AutoTextView mTextView02;
	final Handler handler = new Handler();
	// 自定义信息条数
	private static int sCount = 0;
	private List<String> str = new ArrayList<String>();
	private HorizonScrollTextView tv_2;
	private HorizonScrollTextView2 tv_3;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		init();
	}

	private void init() {
		//垂直滚动
		// 初始化数据
		str.add("信息1");
		str.add("信息2");
		str.add("信息3");
		sCount = str.size();
		mTextView02 = (AutoTextView) findViewById(R.id.switcher02);
		mTextView02.setText(str.get(0));
		//启动计时器
		handler.postDelayed(runnable, 5000);
		//handler.removeCallbacks(runnable);// 关闭定时器处理
		
		//水平滚动
		tv_2 = (HorizonScrollTextView)findViewById(R.id.tv_2);
		tv_2.setText("暂无任何预警信息!     暂无任何预警信息!2        暂无任何预警信息!3          暂无任何预警信息!4    "); 
		tv_2.setTextSize(20);  
		tv_2.setTextColor(Color.WHITE); 
		
		//水平滚动2
		tv_3= (HorizonScrollTextView2)findViewById(R.id.tv_3);
		tv_3.setText("金佛IE我就       佛i就困了睡         多久就分手快乐             大家束带结发");
		tv_3.init(getWindowManager());
		tv_3.startScroll();

	}

	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			// 在此处添加执行的代码
			mTextView02.next();
			sCount++;
			if(sCount>=Integer.MAX_VALUE){
				sCount = str.size();
			}
			mTextView02.setText(str.get(sCount % (str.size())));
			if (str.size()>1) {
				handler.postDelayed(this, 5000);// 50是延时时长
			}
			
		}
	};

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.next:
			mTextView02.next();
			sCount++;
			break;
		case R.id.prev:
			mTextView02.previous();
			sCount--;
			break;
		}
		// mTextView02.setText(sCount%2==0 ?
		// sCount+"AAFirstAA" :
		// sCount+"BBBBBBB");
		mTextView02.setText(str.get(sCount % 3));
		System.out.println("getH: [" + mTextView02.getHeight() + "]");

	}
           

AutoTextView 类

处理文字翻滚和左右移动
public class AutoTextView extends TextSwitcher implements
		ViewSwitcher.ViewFactory {

	private float mHeight;
	private Context mContext;
	//mInUp,mOutUp分别构成向下翻页的进出动画
	private Rotate3dAnimation mInUp;
	private Rotate3dAnimation mOutUp;
	
	//mInDown,mOutDown分别构成向下翻页的进出动画
	private Rotate3dAnimation mInDown;
	private Rotate3dAnimation mOutDown;
	
	public AutoTextView(Context context) {
		this(context, null);
		// TODO Auto-generated constructor stub
	}

	public AutoTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.auto3d);
		//mHeight = a.getDimension(R.styleable.auto3d_textSize, 36);
		mHeight=20;
		a.recycle();
		mContext = context;
		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		setFactory(this);
		mInUp = createAnim(-90, 0 , true, true);
		mOutUp = createAnim(0, 90, false, true);
		mInDown = createAnim(90, 0 , true , false);
		mOutDown = createAnim(0, -90, false, false);
		//TextSwitcher主要用于文件切换,比如 从文字A 切换到 文字 B,
		//setInAnimation()后,A将执行inAnimation,
		//setOutAnimation()后,B将执行OutAnimation
        setInAnimation(mInUp);
        setOutAnimation(mOutUp);
	}
	
	private Rotate3dAnimation createAnim(float start, float end, boolean turnIn, boolean turnUp){
        final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end, turnIn, turnUp);
        //动画持续时间
        rotation.setDuration(300);
        rotation.setFillAfter(false);
        rotation.setInterpolator(new AccelerateInterpolator());
        return rotation;
	}
	
	public void setData(){
		
	}

	//这里返回的TextView,就是我们看到的View
	@Override
	public View makeView() {
		// TODO Auto-generated method stub
		TextView t = new TextView(mContext);
		t.setGravity(Gravity.CENTER);
		t.setTextSize(mHeight);
		t.setMaxLines(2);
		t.setPadding(0, 5, 0, 5);
		//设置文字颜色
		t.setTextColor(Color.WHITE);
		return t;
	}
	//定义动作,向下滚动翻页
	public void previous(){
		if(getInAnimation() != mInDown){
			setInAnimation(mInDown);
		}
		if(getOutAnimation() != mOutDown){
			setOutAnimation(mOutDown);
		}
	}
	//定义动作,向上滚动翻页
	public void next(){
		if(getInAnimation() != mInUp){
			setInAnimation(mInUp);
		}
		if(getOutAnimation() != mOutUp){
			setOutAnimation(mOutUp);
		}
	}
	
	 class Rotate3dAnimation extends Animation {
		    private final float mFromDegrees;
		    private final float mToDegrees;
		    private float mCenterX;
		    private float mCenterY;
		    private final boolean mTurnIn;
		    private final boolean mTurnUp;
		    private Camera mCamera;

		    public Rotate3dAnimation(float fromDegrees, float toDegrees, boolean turnIn, boolean turnUp) {
		        mFromDegrees = fromDegrees;
		        mToDegrees = toDegrees;
		        mTurnIn = turnIn;
		        mTurnUp = turnUp;
		    }

		    @Override
		    public void initialize(int width, int height, int parentWidth, int parentHeight) {
		        super.initialize(width, height, parentWidth, parentHeight);
		        mCamera = new Camera();
		        mCenterY = getHeight() / 2;
		        mCenterX = getWidth() / 2;
		    }
		    
		    @Override
		    protected void applyTransformation(float interpolatedTime, Transformation t) {
		        final float fromDegrees = mFromDegrees;
		        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

		        final float centerX = mCenterX ;
		        final float centerY = mCenterY ;
		        final Camera camera = mCamera;
		        final int derection = mTurnUp ? 1: -1;

		        final Matrix matrix = t.getMatrix();

		        camera.save();
		        if (mTurnIn) {
		            camera.translate(0.0f, derection *mCenterY * (interpolatedTime - 1.0f), 0.0f);
		        } else {
		            camera.translate(0.0f, derection *mCenterY * (interpolatedTime), 0.0f);
		        }
		        camera.rotateX(degrees);
		        camera.getMatrix(matrix);
		        camera.restore();

		        matrix.preTranslate(-centerX, -centerY);
		        matrix.postTranslate(centerX, centerY);
		    }
	 }
}
           

HorizonScrollTextView 类

public class HorizonScrollTextView extends TextView{
	private boolean mStopMarquee;  
    private String mText;  
    private float mCoordinateX;  
    private float mTextWidth;  
   
   
    public HorizonScrollTextView(Context context, AttributeSet attrs) {  
        super(context, attrs);  
    }  
   
   
    public void setText(String text) {  
        this.mText = text;  
        mTextWidth = getPaint().measureText(mText);  
        if (mHandler.hasMessages(0))  
            mHandler.removeMessages(0);  
        mHandler.sendEmptyMessageDelayed(0, 2000);  
    }  
   
    
    @Override 
    protected void onAttachedToWindow() {  
        mStopMarquee = false;  
        if (!(mText == null || mText.isEmpty()))  
            mHandler.sendEmptyMessageDelayed(0, 2000);  
        super.onAttachedToWindow();  
    }  
   
   
    @Override 
    protected void onDetachedFromWindow() {  
        mStopMarquee = true;  
        if (mHandler.hasMessages(0))  
            mHandler.removeMessages(0);  
        super.onDetachedFromWindow();  
    }  
   
   
  
    @Override 
    protected void onDraw(Canvas canvas) {  
        super.onDraw(canvas);  
        if (!(mText == null || mText.isEmpty()))  
            canvas.drawText(mText, mCoordinateX, 30, getPaint());  
    }  
   
    private Handler mHandler = new Handler() {  
        @Override 
        public void handleMessage(Message msg) {  
            switch (msg.what) {  
            case 0:  
                if (Math.abs(mCoordinateX) > (mTextWidth + 5)) {  
                    mCoordinateX = 0;  
                    invalidate();  
                    if (!mStopMarquee) {  
                        sendEmptyMessageDelayed(0,500);  
                    }  
                } else {  
                    mCoordinateX -= 1;  
                    invalidate();  
                    if (!mStopMarquee) {  
                        sendEmptyMessageDelayed(0, 30);  
                    }  
                }  
                break;  
            }  
            super.handleMessage(msg);  
        }  
    }; 
}
           

HorizonScrollTextView2 类

public class HorizonScrollTextView2 extends TextView implements OnClickListener {
	private float textLength = 0f;// 文本长度
	private float viewWidth = 0f;
	private float step = 0f;// 文字的横坐标
	private float y = 0f;// 文字的纵坐标
	private float temp_view_plus_text_length = 0.0f;// 用于计算的临时变量
	private float temp_view_plus_two_text_length = 0.0f;// 用于计算的临时变量
	public boolean isStarting = false;// 是否开始滚动
	private Paint paint = null;// 绘图样式
	private String text = "";// 文本内容

	public HorizonScrollTextView2(Context context) {
		super(context);
		initView();
	}

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

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

	private void initView() {
		setOnClickListener(this);
	}

	public void init(WindowManager windowManager) {
		paint = getPaint();
		//设置滚动字体颜色
		paint.setColor(Color.WHITE);
		text = getText().toString();
		textLength = paint.measureText(text);
		viewWidth = getWidth();
		if (viewWidth == 0) {
			if (windowManager != null) {
				Display display = windowManager.getDefaultDisplay();
				viewWidth = display.getWidth();
			}
		}
		step = textLength;
		temp_view_plus_text_length = viewWidth + textLength;
		temp_view_plus_two_text_length = viewWidth + textLength * 2;
		y = getTextSize() + getPaddingTop();
	}

	@Override
	public Parcelable onSaveInstanceState() {
		Parcelable superState = super.onSaveInstanceState();
		SavedState ss = new SavedState(superState);

		ss.step = step;
		ss.isStarting = isStarting;

		return ss;

	}

	@Override
	public void onRestoreInstanceState(Parcelable state) {
		if (!(state instanceof SavedState)) {
			super.onRestoreInstanceState(state);
			return;
		}
		SavedState ss = (SavedState) state;
		super.onRestoreInstanceState(ss.getSuperState());

		step = ss.step;
		isStarting = ss.isStarting;
	}

	public static class SavedState extends BaseSavedState {
		public boolean isStarting = false;
		public float step = 0.0f;

		SavedState(Parcelable superState) {
			super(superState);
		}

		@Override
		public void writeToParcel(Parcel out, int flags) {
			super.writeToParcel(out, flags);
			out.writeBooleanArray(new boolean[] { isStarting });
			out.writeFloat(step);
		}

		public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {

			public SavedState[] newArray(int size) {
				return new SavedState[size];
			}

			@Override
			public SavedState createFromParcel(Parcel in) {
				return new SavedState(in);
			}
		};

		private SavedState(Parcel in) {
			super(in);
			boolean[] b = null;
			in.readBooleanArray(b);
			if (b != null && b.length > 0)
				isStarting = b[0];
			step = in.readFloat();
		}
	}

	public void startScroll() {
		isStarting = true;
		invalidate();
	}

	public void stopScroll() {
		isStarting = false;
		invalidate();
	}

	@Override
	public void onDraw(Canvas canvas) {
		canvas.drawText(text, temp_view_plus_text_length - step, y, paint);
		if (!isStarting) {
			return;
		}
		step += 0.8;// 0.5为文字滚动速度。
		if (step > temp_view_plus_two_text_length)
			step = textLength;
		invalidate();
	}

	//控制点击停止或者继续运行
	@Override
	public void onClick(View v) {
		if (isStarting)
			stopScroll();
		else
			startScroll();

	}
}
           
最后附上源码地址:http://download.csdn.net/detail/u014608640/9626180